diff --git a/experimental/CHANGELOG.md b/experimental/CHANGELOG.md index f4bf066fe19..23be231c1ff 100644 --- a/experimental/CHANGELOG.md +++ b/experimental/CHANGELOG.md @@ -34,6 +34,7 @@ For notes on migrating to 2.x / 0.200.x see [the upgrade guide](doc/upgrade-to-2 * feat(sdk-node): wire up metric producers from declarative config [#6712](https://github.com/open-telemetry/opentelemetry-js/pull/6712) @MikeGoldsmith * feat(sdk-logs)!: add support for attributes in LoggerOptions [#6573](https://github.com/open-telemetry/opentelemetry-js/pull/6573) @pichlermarc +* feat(propagator-env-carrier): add environment variable carrier helpers for context propagation [#6774](https://github.com/open-telemetry/opentelemetry-js/pull/6774) @pellared ### :bug: Bug Fixes diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/LICENSE b/experimental/packages/opentelemetry-propagator-env-carrier/LICENSE new file mode 100644 index 00000000000..261eeb9e9f8 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/README.md b/experimental/packages/opentelemetry-propagator-env-carrier/README.md new file mode 100644 index 00000000000..c876aef0abb --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/README.md @@ -0,0 +1,121 @@ +# OpenTelemetry Environment Propagation Carrier + +[![NPM Published Version][npm-img]][npm-url] +[![Apache License][license-image]][license-image] + +This package provides environment variable carrier helpers for use with +OpenTelemetry `TextMapPropagator` implementations. + +It follows the OpenTelemetry +[Environment Variables as Context Propagation Carriers][env-carrier-spec] +specification. The carrier helpers are format-agnostic and treat values as +opaque strings. Propagators such as W3C Trace Context and W3C Baggage remain +responsible for choosing keys, parsing values, and validating propagation +formats. + +## Usage + +Use `EnvironmentSetter` to inject context into an environment map owned by your +application. Pass the map to `EnvironmentSetter`, and pass `undefined` as the +carrier when injecting. The map can then be passed to a child process. +`EnvironmentSetter` writes only to the map supplied to its constructor and does +not modify `process.env`. + +```javascript +const { execFileSync } = require('node:child_process'); +const { ROOT_CONTEXT, trace, TraceFlags } = require('@opentelemetry/api'); +const { W3CTraceContextPropagator } = require('@opentelemetry/core'); +const { + EnvironmentSetter, +} = require('@opentelemetry/propagator-env-carrier'); + +const ctx = trace.setSpanContext(ROOT_CONTEXT, { + traceId: '0102030405060708090a0b0c0d0e0f10', + spanId: '0102030405060708', + traceFlags: TraceFlags.SAMPLED, +}); +const env = { ...process.env }; +const propagator = new W3CTraceContextPropagator(); + +propagator.inject(ctx, undefined, new EnvironmentSetter(env)); + +const output = execFileSync( + process.execPath, + ['-e', 'process.stdout.write(process.env.TRACEPARENT ?? "")'], + { env, encoding: 'utf8' } +); + +console.log(output); +// 00-0102030405060708090a0b0c0d0e0f10-0102030405060708-01 +``` + +Use `EnvironmentGetter` during process startup to extract context that was +provided through environment variables. It reads from its own snapshot, so pass +`undefined` as the carrier when extracting. + +```javascript +const { ROOT_CONTEXT, trace } = require('@opentelemetry/api'); +const { W3CTraceContextPropagator } = require('@opentelemetry/core'); +const { + EnvironmentGetter, +} = require('@opentelemetry/propagator-env-carrier'); + +const propagator = new W3CTraceContextPropagator(); +const context = propagator.extract( + ROOT_CONTEXT, + undefined, + new EnvironmentGetter() +); +const spanContext = trace.getSpanContext(context); + +console.log(spanContext.traceId); +// 0102030405060708090a0b0c0d0e0f10 +``` + +`EnvironmentGetter` snapshots `process.env` when it is constructed. Later +changes to `process.env` are not reflected in that getter. Only environment +variables whose names are already normalized are included in the snapshot. + +## Key Normalization + +Environment variable names used for propagation are normalized by: + +- uppercasing ASCII letters, +- replacing every character that is not an ASCII letter, digit, or underscore + with an underscore, +- prefixing the name with an underscore if it would otherwise start with an + ASCII digit. + +For example, `traceparent` becomes `TRACEPARENT`, `trace-state` becomes +`TRACE_STATE`, and `1abc` becomes `_1ABC`. + +`EnvironmentSetter` always writes normalized key names to its environment map. +`EnvironmentGetter` normalizes the requested propagator key and reads the +corresponding normalized environment variable name from its snapshot. Its +`keys()` method returns only environment variable names that are already +normalized. For example, a propagator request for `x-b3-traceid` matches +`X_B3_TRACEID` from `process.env`, but does not match `x-b3-traceid`. + +Name collisions after normalization should be avoided. For example, +`trace-state` and `TRACE_STATE` both normalize to `TRACE_STATE`. When injecting, +later writes to the same normalized name replace earlier values in the target +map. + +## Useful links + +- OpenTelemetry Environment Variables as Context Propagation Carriers specification: + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[env-carrier-spec]: https://opentelemetry.io/docs/specs/otel/context/env-carriers/ +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[npm-url]: https://www.npmjs.com/package/@opentelemetry/propagator-env-carrier +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fpropagator-env-carrier.svg diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/package.json b/experimental/packages/opentelemetry-propagator-env-carrier/package.json new file mode 100644 index 00000000000..c78b13b18ec --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/package.json @@ -0,0 +1,64 @@ +{ + "name": "@opentelemetry/propagator-env-carrier", + "version": "0.219.0", + "description": "OpenTelemetry environment variable carrier helpers for context propagation", + "main": "build/src/index.js", + "module": "build/esm/index.js", + "esnext": "build/esnext/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "prepublishOnly": "npm run compile", + "compile": "tsc --build tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "clean": "tsc --build --clean tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "test": "nyc mocha 'test/**/*.test.ts'", + "lint": "eslint .", + "lint:fix": "eslint . --fix", + "version": "node ../../../scripts/version-update.js", + "watch": "tsc --build --watch tsconfig.json tsconfig.esm.json tsconfig.esnext.json", + "prewatch": "npm run precompile", + "peer-api-check": "node ../../../scripts/peer-api-check.js", + "align-api-deps": "node ../../../scripts/align-api-deps.js" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "propagation", + "environment" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "files": [ + "build/esm/**/*.js", + "build/esm/**/*.js.map", + "build/esm/**/*.d.ts", + "build/esnext/**/*.js", + "build/esnext/**/*.js.map", + "build/esnext/**/*.d.ts", + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + }, + "devDependencies": { + "@opentelemetry/api": "1.9.1", + "@opentelemetry/core": "2.8.0", + "@types/mocha": "10.0.10", + "@types/node": "18.19.130", + "mocha": "11.7.5", + "nyc": "17.1.0", + "typescript": "5.0.4" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-propagator-env-carrier", + "sideEffects": false +} diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/src/env-carrier.ts b/experimental/packages/opentelemetry-propagator-env-carrier/src/env-carrier.ts new file mode 100644 index 00000000000..f0f6caa4cc5 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/src/env-carrier.ts @@ -0,0 +1,147 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +import type { TextMapGetter, TextMapSetter } from '@opentelemetry/api'; + +const ASCII_UPPER_A = 'A'.charCodeAt(0); +const ASCII_UPPER_Z = 'Z'.charCodeAt(0); +const ASCII_LOWER_A = 'a'.charCodeAt(0); +const ASCII_LOWER_Z = 'z'.charCodeAt(0); +const ASCII_DIGIT_0 = '0'.charCodeAt(0); +const ASCII_DIGIT_9 = '9'.charCodeAt(0); +const ASCII_UNDERSCORE = '_'.charCodeAt(0); +const ASCII_CASE_OFFSET = ASCII_LOWER_A - ASCII_UPPER_A; + +/** + * isNormalizedKey returns whether a key is already a normalized environment variable name. + * + * A normalized name is non-empty, starts with an ASCII uppercase letter or + * underscore, and contains only ASCII uppercase letters, digits, and + * underscores. Equivalently, it matches /^[A-Z_][A-Z0-9_]*$/. + */ +function isNormalizedKey(key: string): boolean { + if (key.length === 0) { + return false; + } + + const firstCharCode = key.charCodeAt(0); + if ( + !( + (firstCharCode >= ASCII_UPPER_A && firstCharCode <= ASCII_UPPER_Z) || + firstCharCode === ASCII_UNDERSCORE + ) + ) { + return false; + } + + for (let i = 1; i < key.length; i++) { + const charCode = key.charCodeAt(i); + + if ( + !( + (charCode >= ASCII_UPPER_A && charCode <= ASCII_UPPER_Z) || + (charCode >= ASCII_DIGIT_0 && charCode <= ASCII_DIGIT_9) || + charCode === ASCII_UNDERSCORE + ) + ) { + return false; + } + } + + return true; +} + +/** + * normalizeKey converts a propagator key to a valid POSIX environment variable + * name. The conversion rules are: + * - A-Z, 0-9, and _ are kept as-is. + * - a-z are uppercased. + * - All other characters are replaced with _. + * - If the result would start with a digit, an underscore is prepended. + */ +function normalizeKey(key: string): string { + let result = ''; + + for (let i = 0; i < key.length; i++) { + const charCode = key.charCodeAt(i); + + if (charCode >= ASCII_LOWER_A && charCode <= ASCII_LOWER_Z) { + result += String.fromCharCode(charCode - ASCII_CASE_OFFSET); + } else if ( + (charCode >= ASCII_UPPER_A && charCode <= ASCII_UPPER_Z) || + (charCode >= ASCII_DIGIT_0 && charCode <= ASCII_DIGIT_9) || + charCode === ASCII_UNDERSCORE + ) { + result += key[i]; + } else { + result += '_'; + } + } + + const firstCharCode = result.charCodeAt(0); + if (firstCharCode >= ASCII_DIGIT_0 && firstCharCode <= ASCII_DIGIT_9) { + return `_${result}`; + } + + return result; +} + +/** + * TextMapGetter that reads propagation values from a process environment + * snapshot. + * + * `EnvironmentGetter` snapshots `process.env` when it is constructed and + * ignores the carrier passed to `get()` and `keys()`. Pass `undefined` as the + * carrier when using this getter with a `TextMapPropagator`. + * + * Only environment variables whose names are already normalized are stored in + * the snapshot. The requested propagator key is normalized before lookup. + * + * @see https://opentelemetry.io/docs/specs/otel/context/env-carriers/ + */ +export class EnvironmentGetter implements TextMapGetter { + private readonly _carrier: Record = {}; + + constructor() { + for (const [key, value] of Object.entries(process.env)) { + if (value !== undefined && isNormalizedKey(key)) { + this._carrier[key] = value; + } + } + } + + get(_carrier: void, key: string): string | undefined { + return this._carrier[normalizeKey(key)]; + } + + keys(_carrier: void): string[] { + return Object.keys(this._carrier); + } +} + +/** + * TextMapSetter that writes propagation values to an environment map. + * + * `EnvironmentSetter` mutates only the environment map supplied to the + * constructor and never writes to `process.env`. Pass `undefined` as the + * carrier when using this setter with a `TextMapPropagator`. + * + * Propagator keys are normalized before storing their opaque string values. If + * multiple keys normalize to the same environment variable name, the latest + * value written to the map is retained. + * + * @see https://opentelemetry.io/docs/specs/otel/context/env-carriers/ + */ +export class EnvironmentSetter implements TextMapSetter { + private readonly _carrier: Record; + + constructor(carrier: Record) { + this._carrier = carrier; + } + + set(_carrier: void, key: string, value: string): void { + this._carrier[normalizeKey(key)] = value; + } +} diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/src/index.ts b/experimental/packages/opentelemetry-propagator-env-carrier/src/index.ts new file mode 100644 index 00000000000..ed540b3d430 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/src/index.ts @@ -0,0 +1,6 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +export { EnvironmentGetter, EnvironmentSetter } from './env-carrier'; diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/test/env-carrier.test.ts b/experimental/packages/opentelemetry-propagator-env-carrier/test/env-carrier.test.ts new file mode 100644 index 00000000000..aa692530038 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/test/env-carrier.test.ts @@ -0,0 +1,319 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as assert from 'assert'; + +import { + propagation, + ROOT_CONTEXT, + trace, + TraceFlags, +} from '@opentelemetry/api'; +import { + TraceState, + W3CBaggagePropagator, + W3CTraceContextPropagator, +} from '@opentelemetry/core'; + +import { EnvironmentGetter, EnvironmentSetter } from '../src'; + +describe('EnvironmentGetter and EnvironmentSetter', () => { + const originalEnv = { ...process.env }; + + beforeEach(() => { + clearEnv(); + }); + + afterEach(() => { + clearEnv(); + Object.assign(process.env, originalEnv); + }); + + describe('EnvironmentSetter', () => { + it('should normalize keys when setting values', () => { + const carrier: Record = {}; + const setter = new EnvironmentSetter(carrier); + + setter.set(undefined, 'traceparent', 'traceparent-value'); + setter.set(undefined, 'trace-state', 'tracestate-value'); + setter.set(undefined, 'foo.bar', 'dot-value'); + setter.set(undefined, 'MiXeD_cAsE', 'mixed-value'); + setter.set(undefined, 'h\u00e9llo', 'non-ascii-value'); + setter.set(undefined, '1abc', 'leading-digit-value'); + + assert.deepStrictEqual(carrier, { + TRACEPARENT: 'traceparent-value', + TRACE_STATE: 'tracestate-value', + FOO_BAR: 'dot-value', + MIXED_CASE: 'mixed-value', + H_LLO: 'non-ascii-value', + _1ABC: 'leading-digit-value', + }); + }); + + it('should preserve digits and underscores when normalizing keys', () => { + const carrier: Record = {}; + const setter = new EnvironmentSetter(carrier); + + setter.set(undefined, 'a_1-b_2', 'value'); + + assert.deepStrictEqual(carrier, { + A_1_B_2: 'value', + }); + }); + + it('should overwrite values with the same normalized key', () => { + const carrier: Record = {}; + const setter = new EnvironmentSetter(carrier); + + setter.set(undefined, 'trace-state', 'first'); + setter.set(undefined, 'TRACE_STATE', 'second'); + + assert.deepStrictEqual(carrier, { + TRACE_STATE: 'second', + }); + }); + + it('should treat values as opaque strings', () => { + const carrier: Record = {}; + const setter = new EnvironmentSetter(carrier); + + setter.set(undefined, 'empty', ''); + setter.set(undefined, 'whitespace', ' value '); + + assert.deepStrictEqual(carrier, { + EMPTY: '', + WHITESPACE: ' value ', + }); + }); + + it('should not modify process.env', () => { + const carrier: Record = {}; + const setter = new EnvironmentSetter(carrier); + + setter.set(undefined, 'traceparent', 'value'); + + assert.deepStrictEqual(Object.keys(process.env), []); + assert.deepStrictEqual(carrier, { TRACEPARENT: 'value' }); + }); + }); + + describe('EnvironmentGetter', () => { + it('should normalize keys when reading values', () => { + process.env.TRACEPARENT = 'traceparent-value'; + process.env.TRACE_STATE = 'tracestate-value'; + process.env.FOO_BAR = 'dot-value'; + process.env.MIXED_CASE = 'mixed-value'; + process.env.H_LLO = 'non-ascii-value'; + process.env._1ABC = 'leading-digit-value'; + process.env.X_B3_TRACEID = 'b3-value'; + + const getter = new EnvironmentGetter(); + + assert.strictEqual( + getter.get(undefined, 'traceparent'), + 'traceparent-value' + ); + assert.strictEqual( + getter.get(undefined, 'trace-state'), + 'tracestate-value' + ); + assert.strictEqual(getter.get(undefined, 'foo.bar'), 'dot-value'); + assert.strictEqual(getter.get(undefined, 'MiXeD_cAsE'), 'mixed-value'); + assert.strictEqual( + getter.get(undefined, 'h\u00e9llo'), + 'non-ascii-value' + ); + assert.strictEqual(getter.get(undefined, '1abc'), 'leading-digit-value'); + assert.strictEqual(getter.get(undefined, 'X_B3_TRACEID'), 'b3-value'); + assert.strictEqual(getter.get(undefined, 'x-b3-traceid'), 'b3-value'); + }); + + it('should return only already normalized snapshot keys', () => { + process.env.TRACEPARENT = 'traceparent-value'; + process.env.TRACE_STATE = 'tracestate-value'; + process.env['trace-state'] = 'ignored'; + process.env['X-B3-TRACEID'] = 'ignored'; + process.env['1ABC'] = 'ignored'; + + const getter = new EnvironmentGetter(); + + assert.deepStrictEqual(getter.keys(undefined).sort(), [ + 'TRACEPARENT', + 'TRACE_STATE', + ]); + }); + + it('should return empty keys for an empty environment snapshot', () => { + const getter = new EnvironmentGetter(); + + assert.deepStrictEqual(getter.keys(undefined), []); + }); + + it('should ignore empty environment names when snapshotting', () => { + const env = process.env; + process.env = { + '': 'ignored', + TRACEPARENT: 'traceparent-value', + }; + + try { + const getter = new EnvironmentGetter(); + + assert.deepStrictEqual(getter.keys(undefined), ['TRACEPARENT']); + assert.strictEqual(getter.get(undefined, ''), undefined); + } finally { + process.env = env; + } + }); + + it('should return undefined when a key is missing', () => { + process.env.TRACEPARENT = 'traceparent-value'; + + const getter = new EnvironmentGetter(); + + assert.strictEqual(getter.get(undefined, 'tracestate'), undefined); + }); + + it('should ignore non-normalized environment names when reading values', () => { + process.env.traceparent = 'ignored'; + process.env['trace-state'] = 'ignored'; + process.env['x-b3-traceid'] = 'ignored'; + process.env['1ABC'] = 'ignored'; + + const getter = new EnvironmentGetter(); + + assert.strictEqual(getter.get(undefined, 'traceparent'), undefined); + assert.strictEqual(getter.get(undefined, 'trace-state'), undefined); + assert.strictEqual(getter.get(undefined, 'x-b3-traceid'), undefined); + assert.strictEqual(getter.get(undefined, '1abc'), undefined); + assert.deepStrictEqual(getter.keys(undefined), []); + }); + + it('should preserve empty string values', () => { + process.env.EMPTY = ''; + + const getter = new EnvironmentGetter(); + + assert.strictEqual(getter.get(undefined, 'empty'), ''); + }); + + it('should snapshot process.env at construction time', () => { + process.env.TRACEPARENT = 'original'; + const getter = new EnvironmentGetter(); + + process.env.TRACEPARENT = 'updated'; + process.env.TRACESTATE = 'added-after-construction'; + + assert.strictEqual(getter.get(undefined, 'traceparent'), 'original'); + assert.strictEqual(getter.get(undefined, 'tracestate'), undefined); + }); + + it('should read from the environment snapshot without a carrier', () => { + process.env.TRACEPARENT = 'environment-value'; + + const getter = new EnvironmentGetter(); + + assert.strictEqual( + getter.get(undefined, 'traceparent'), + 'environment-value' + ); + }); + }); + + describe('propagator integration', () => { + const traceId = '4bf92f3577b34da6a3ce929d0e0e4736'; + const spanId = '00f067aa0ba902b7'; + + it('should inject W3C trace context into an environment carrier', () => { + const propagator = new W3CTraceContextPropagator(); + const context = trace.setSpanContext(ROOT_CONTEXT, { + traceId, + spanId, + traceFlags: TraceFlags.SAMPLED, + traceState: new TraceState('vendor1=value1,vendor2=value2'), + }); + const carrier: Record = {}; + + propagator.inject(context, undefined, new EnvironmentSetter(carrier)); + + assert.deepStrictEqual(carrier, { + TRACEPARENT: `00-${traceId}-${spanId}-01`, + TRACESTATE: 'vendor1=value1,vendor2=value2', + }); + }); + + it('should extract W3C trace context from an environment snapshot', () => { + process.env.TRACEPARENT = `00-${traceId}-${spanId}-01`; + process.env.TRACESTATE = 'vendor1=value1,vendor2=value2'; + + const propagator = new W3CTraceContextPropagator(); + const context = propagator.extract( + ROOT_CONTEXT, + undefined, + new EnvironmentGetter() + ); + const spanContext = trace.getSpanContext(context); + + assert.strictEqual(spanContext?.traceId, traceId); + assert.strictEqual(spanContext?.spanId, spanId); + assert.strictEqual(spanContext?.traceFlags, TraceFlags.SAMPLED); + assert.strictEqual(spanContext?.isRemote, true); + assert.strictEqual(spanContext?.traceState?.get('vendor1'), 'value1'); + assert.strictEqual(spanContext?.traceState?.get('vendor2'), 'value2'); + }); + + it('should ignore W3C trace context in non-normalized environment names', () => { + process.env.traceparent = `00-${traceId}-${spanId}-01`; + process.env.tracestate = 'vendor1=value1,vendor2=value2'; + + const propagator = new W3CTraceContextPropagator(); + const context = propagator.extract( + ROOT_CONTEXT, + undefined, + new EnvironmentGetter() + ); + + assert.strictEqual(trace.getSpanContext(context), undefined); + }); + + it('should inject W3C baggage into an environment carrier', () => { + const propagator = new W3CBaggagePropagator(); + const context = propagation.setBaggage( + ROOT_CONTEXT, + propagation.createBaggage({ + first: { value: 'one' }, + second: { value: 'two' }, + }) + ); + const carrier: Record = {}; + + propagator.inject(context, undefined, new EnvironmentSetter(carrier)); + + assert.strictEqual(carrier.BAGGAGE, 'first=one,second=two'); + }); + + it('should extract W3C baggage from an environment snapshot', () => { + process.env.BAGGAGE = 'first=one,second=two'; + + const propagator = new W3CBaggagePropagator(); + const context = propagator.extract( + ROOT_CONTEXT, + undefined, + new EnvironmentGetter() + ); + const baggage = propagation.getBaggage(context); + + assert.strictEqual(baggage?.getEntry('first')?.value, 'one'); + assert.strictEqual(baggage?.getEntry('second')?.value, 'two'); + }); + }); +}); + +function clearEnv() { + for (const key of Object.keys(process.env)) { + delete process.env[key]; + } +} diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esm.json b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esm.json new file mode 100644 index 00000000000..ae474033346 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esm.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../tsconfig.base.esm.json", + "compilerOptions": { + "outDir": "build/esm", + "rootDir": "src", + "tsBuildInfoFile": "build/esm/tsconfig.esm.tsbuildinfo" + }, + "include": [ + "src/**/*.ts" + ], + "references": [ + { + "path": "../../../api" + }, + { + "path": "../../../packages/opentelemetry-core" + } + ] +} diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esnext.json b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esnext.json new file mode 100644 index 00000000000..5f6cf572d5a --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esnext.json @@ -0,0 +1,19 @@ +{ + "extends": "../../../tsconfig.base.esnext.json", + "compilerOptions": { + "outDir": "build/esnext", + "rootDir": "src", + "tsBuildInfoFile": "build/esnext/tsconfig.esnext.tsbuildinfo" + }, + "include": [ + "src/**/*.ts" + ], + "references": [ + { + "path": "../../../api" + }, + { + "path": "../../../packages/opentelemetry-core" + } + ] +} diff --git a/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.json b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.json new file mode 100644 index 00000000000..6feabd64655 --- /dev/null +++ b/experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.json @@ -0,0 +1,20 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "outDir": "build", + "rootDir": "." + }, + "files": [], + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ], + "references": [ + { + "path": "../../../api" + }, + { + "path": "../../../packages/opentelemetry-core" + } + ] +} diff --git a/package-lock.json b/package-lock.json index 6c3bf525395..badc54ca4d0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1371,6 +1371,26 @@ "@opentelemetry/api": "^1.3.0" } }, + "experimental/packages/opentelemetry-propagator-env-carrier": { + "name": "@opentelemetry/propagator-env-carrier", + "version": "0.219.0", + "license": "Apache-2.0", + "devDependencies": { + "@opentelemetry/api": "1.9.1", + "@opentelemetry/core": "2.8.0", + "@types/mocha": "10.0.10", + "@types/node": "18.19.130", + "mocha": "11.7.5", + "nyc": "17.1.0", + "typescript": "5.0.4" + }, + "engines": { + "node": "^18.19.0 || >=20.6.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.3.0" + } + }, "experimental/packages/opentelemetry-sdk-node": { "name": "@opentelemetry/sdk-node", "version": "0.219.0", @@ -6266,6 +6286,10 @@ "resolved": "packages/opentelemetry-propagator-b3", "link": true }, + "node_modules/@opentelemetry/propagator-env-carrier": { + "resolved": "experimental/packages/opentelemetry-propagator-env-carrier", + "link": true + }, "node_modules/@opentelemetry/propagator-jaeger": { "resolved": "packages/opentelemetry-propagator-jaeger", "link": true diff --git a/tsconfig.esm.json b/tsconfig.esm.json index 6323b1a05d4..9e60a65d022 100644 --- a/tsconfig.esm.json +++ b/tsconfig.esm.json @@ -38,6 +38,9 @@ { "path": "experimental/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.esm.json" }, + { + "path": "experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esm.json" + }, { "path": "experimental/packages/otlp-exporter-base/tsconfig.esm.json" }, diff --git a/tsconfig.esnext.json b/tsconfig.esnext.json index 576e207d761..34e9d1124e9 100644 --- a/tsconfig.esnext.json +++ b/tsconfig.esnext.json @@ -38,6 +38,9 @@ { "path": "experimental/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.esnext.json" }, + { + "path": "experimental/packages/opentelemetry-propagator-env-carrier/tsconfig.esnext.json" + }, { "path": "experimental/packages/otlp-exporter-base/tsconfig.esnext.json" }, diff --git a/tsconfig.json b/tsconfig.json index 2977213850a..eeec90f0248 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -23,6 +23,7 @@ "experimental/packages/opentelemetry-instrumentation-grpc", "experimental/packages/opentelemetry-instrumentation-http", "experimental/packages/opentelemetry-instrumentation-xml-http-request", + "experimental/packages/opentelemetry-propagator-env-carrier", "experimental/packages/opentelemetry-sdk-node", "experimental/packages/otlp-exporter-base", "experimental/packages/otlp-grpc-exporter-base", @@ -117,6 +118,9 @@ { "path": "experimental/packages/opentelemetry-instrumentation-xml-http-request" }, + { + "path": "experimental/packages/opentelemetry-propagator-env-carrier" + }, { "path": "experimental/packages/opentelemetry-sdk-node" },