diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ee9489..4598894 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## [Unreleased] +## [1.21.0] - 2026-11-17 + +Packages: `runtime-node` 1.17.0, and the Python adapter (`adapters/python`, copied, not published). The other packages are unchanged; the `otlp-ingester` README is updated without a release. + +### The environment is sent as `deployment.environment.name` + +OpenTelemetry's semantic conventions renamed the resource attribute `deployment.environment` to `deployment.environment.name`. Every Autter ingester version reads both and prefers the new name, so nothing changes in Autter. + +- `runtime-node`: `initAutterServer` sends the environment on spans and metrics as `deployment.environment.name` (log records already did). A value set in `OTEL_RESOURCE_ATTRIBUTES` still wins, under either name: one under the old name is also sent as `deployment.environment.name`, so it keeps winning now that the SDK no longer sends the old name itself. `npx @autter/runtime-node verify` sends its test event with the new name. +- Python adapter: under a test runner, `init_tracing()` sets `deployment.environment.name=test` (was `deployment.environment=test`) when the resource has no environment; an environment the service sets, under either name, still wins and is left as it is. The test event of `python3 compat.py verify` uses the new name. +- Docs and examples set `OTEL_RESOURCE_ATTRIBUTES=…,deployment.environment.name=…`. `deployment.environment` still works. +- **Behaviour change:** a collector or backend of your own that reads `deployment.environment` from Autter's Node spans, or from the Python adapter's test environment, should read `deployment.environment.name` (or both). + ## [1.20.1] - 2026-11-15 Packages: `runtime-browser` 1.8.2, `runtime-node` 1.16.1, `runtime-edge` 1.4.3, `runtime-next` 1.11.1, `runtime-cli` 1.4.1, `otlp-ingester` 1.18.1. No code changes from 1.20.0. diff --git a/adapters/python/autter_tracing.py b/adapters/python/autter_tracing.py index 60f01f8..083faf2 100644 --- a/adapters/python/autter_tracing.py +++ b/adapters/python/autter_tracing.py @@ -56,7 +56,7 @@ Test runs, commit and release. :func:`init_tracing` fills in three resource attributes the service did not set itself (an explicit value always wins): -* ``deployment.environment = test`` when the process runs under a test +* ``deployment.environment.name = test`` when the process runs under a test runner (pytest, or Django's ``manage.py test``) and the resource has no environment at all (neither ``deployment.environment.name`` nor ``deployment.environment``). Off with ``AUTTER_DETECT_TEST_ENV=false`` or @@ -670,10 +670,10 @@ def _with_deployment(resource: Resource, detect_test_env: Optional[bool], detect if detect_test_env if detect_test_env is not None else _env_flag(DETECT_TEST_ENV_ENV, True): runner = detect_test_runner() if runner is not None: - added["deployment.environment"] = _TEST_ENVIRONMENT + added["deployment.environment.name"] = _TEST_ENVIRONMENT LOGGER.info( - "[autter-runtime] test run detected (%s): reporting deployment.environment=test. Set " - "deployment.environment, or AUTTER_DETECT_TEST_ENV=false, to report another environment.", + "[autter-runtime] test run detected (%s): reporting deployment.environment.name=test. Set " + "deployment.environment.name, or AUTTER_DETECT_TEST_ENV=false, to report another environment.", runner, ) if _has_value(attributes, _COMMIT_ATTRIBUTE): @@ -886,7 +886,7 @@ def init_tracing( ``False`` turns it off): under a test runner (:func:`detect_test_runner`: pytest, Django's ``manage.py test``), a resource with neither ``deployment.environment.name`` nor ``deployment.environment`` gets - ``deployment.environment=test``, logged once at info level. + ``deployment.environment.name=test``, logged once at info level. * ``deployment.commit``: the running commit, :func:`detect_commit` (the first of :data:`COMMIT_ENV_VARS` holding 7 to 40 hexadecimal characters; environment variables only), when the resource has none. diff --git a/adapters/python/compat.py b/adapters/python/compat.py index 640a71d..a8aa0d1 100644 --- a/adapters/python/compat.py +++ b/adapters/python/compat.py @@ -824,7 +824,7 @@ def add(step: str, status: str, detail: str, fix: Optional[str] = None) -> None: return done() add("auth", "pass", "key accepted") - resource = {"attributes": [_attr("service.name", service), _attr("deployment.environment", environment), + resource = {"attributes": [_attr("service.name", service), _attr("deployment.environment.name", environment), *([_attr("service.version", release)] if release else []), _attr("autter.verify.id", trace_id)]} end = time.time_ns() diff --git a/adapters/python/test_deployment_detection.py b/adapters/python/test_deployment_detection.py index 7899238..a50f3a5 100644 --- a/adapters/python/test_deployment_detection.py +++ b/adapters/python/test_deployment_detection.py @@ -155,7 +155,8 @@ class TestEnvironment(unittest.TestCase): def test_a_test_run_without_an_environment_reports_test_and_says_so_once(self): with self.assertLogs("autter.runtime", "INFO") as logs: resource = _resource(runner="pytest") - self.assertEqual(resource["deployment.environment"], "test") + self.assertEqual(resource["deployment.environment.name"], "test") + self.assertNotIn("deployment.environment", resource, "only the current semantic-conventions name") lines = [line for line in logs.output if "test run detected" in line] self.assertEqual(len(lines), 1) self.assertIn("INFO", lines[0]) @@ -163,7 +164,7 @@ def test_a_test_run_without_an_environment_reports_test_and_says_so_once(self): def test_a_passed_resource_without_an_environment_also_reports_test(self): resource = _resource(runner="manage.py test", resource=Resource.create({"service.name": "shop"})) - self.assertEqual(resource["deployment.environment"], "test") + self.assertEqual(resource["deployment.environment.name"], "test") self.assertEqual(resource["service.name"], "shop") def test_an_explicit_environment_always_wins(self): @@ -196,11 +197,13 @@ def test_opt_outs(self): ({"AUTTER_DETECT_TEST_ENV": "true"}, {"detect_test_env": False}), # the argument wins ): with self.subTest(env=env, kwargs=kwargs): - self.assertNotIn("deployment.environment", _resource(env, runner="pytest", **kwargs)) + resource = _resource(env, runner="pytest", **kwargs) + self.assertNotIn("deployment.environment.name", resource) + self.assertNotIn("deployment.environment", resource) # And the argument turns it on over the variable. self.assertEqual( _resource({"AUTTER_DETECT_TEST_ENV": "false"}, runner="pytest", detect_test_env=True)[ - "deployment.environment" + "deployment.environment.name" ], "test", ) @@ -215,7 +218,7 @@ def test_request_counts_carry_the_same_environment_commit_and_release(self): provider.shutdown() metric_resources = metric_exporter.resources() self.assertTrue(metric_resources, "the request was counted") - for key, value in (("deployment.environment", "test"), ("deployment.commit", SHA), ("service.version", SHA)): + for key, value in (("deployment.environment.name", "test"), ("deployment.commit", SHA), ("service.version", SHA)): self.assertEqual(provider.resource.attributes[key], value) for metric_resource in metric_resources: # older SDKs export once more on shutdown self.assertEqual(metric_resource[key], value) @@ -421,12 +424,14 @@ def test_init_tracing_marks_retained_error_spans(self): def test_reports_test(): provider = init_tracing(exporter=InMemorySpanExporter(), set_global=False, count_requests=False) - assert provider.resource.attributes["deployment.environment"] == "test" + assert provider.resource.attributes["deployment.environment.name"] == "test" + assert "deployment.environment" not in provider.resource.attributes def test_explicit_environment_wins(): os.environ["OTEL_RESOURCE_ATTRIBUTES"] = "deployment.environment=production" provider = init_tracing(exporter=InMemorySpanExporter(), set_global=False, count_requests=False) assert provider.resource.attributes["deployment.environment"] == "production" + assert "deployment.environment.name" not in provider.resource.attributes # the old name, set by the user, is kept and wins """ ) diff --git a/adapters/python/test_verify.py b/adapters/python/test_verify.py index fbe17ee..0a629c8 100644 --- a/adapters/python/test_verify.py +++ b/adapters/python/test_verify.py @@ -164,7 +164,8 @@ def test_every_step_passes(self): [(path, body)] = state["posted"][:1] attrs = {a["key"]: a["value"]["stringValue"] for a in body["resourceSpans"][0]["resource"]["attributes"]} self.assertEqual(attrs["autter.verify.id"], report["traceId"]) - self.assertEqual(attrs["deployment.environment"], "verify") + self.assertEqual(attrs["deployment.environment.name"], "verify") + self.assertNotIn("deployment.environment", attrs) finally: server.shutdown() diff --git a/docs/GETTING-STARTED.md b/docs/GETTING-STARTED.md index d48d498..7a4a75d 100644 --- a/docs/GETTING-STARTED.md +++ b/docs/GETTING-STARTED.md @@ -489,7 +489,7 @@ package at all — configure the SDK you already use: OTEL_EXPORTER_OTLP_ENDPOINT=https://your-ingester.example.com OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer ${AUTTER_RUNTIME_KEY}" OTEL_SERVICE_NAME=payments-api -OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.commit=${GIT_SHA},deployment.environment=production +OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.commit=${GIT_SHA},deployment.environment.name=production OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.01 ``` @@ -526,7 +526,7 @@ reports, `test`: | --- | --- | --- | | `@autter/runtime-node` (and `@autter/runtime-next` on the server) | Jest, Vitest or `node --test`, with no `environment` option and no `NODE_ENV` | pass `environment` or set `NODE_ENV` | | `autter_tracing.py` | pytest or Django's `manage.py test`, with no environment on the resource | `AUTTER_DETECT_TEST_ENV=false` or `init_tracing(detect_test_env=False)` | -| Any other OpenTelemetry SDK | set it yourself, e.g. `OTEL_RESOURCE_ATTRIBUTES=deployment.environment=test` in the CI job | | +| Any other OpenTelemetry SDK | set it yourself, e.g. `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=test` in the CI job | | An explicit environment always wins. Autter leaves the `test` environment out of its default views and never pages on it. The ingester never changes diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md index 2b46343..d39782e 100644 --- a/docs/INTEGRATIONS.md +++ b/docs/INTEGRATIONS.md @@ -226,7 +226,7 @@ Configuration is environment variables only: OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.autter.dev # the exporter adds /v1/traces OTEL_EXPORTER_OTLP_HEADERS=x-autter-key=${AUTTER_RUNTIME_KEY} # the server key OTEL_SERVICE_NAME=shop -OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment=production +OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment.name=production OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.01 # 1% of healthy traces; init_tracing() exports every error AUTTER_COUNT_REQUESTS=true # count every request (the default; older copies need it set) @@ -250,11 +250,11 @@ always wins: or `init_tracing(detect_release=False)` turns the release default off; the commit is still sent. - **Test runs.** Running your tests with tracing on? Under pytest or - `manage.py test`, the adapter reports `deployment.environment=test` unless + `manage.py test`, the adapter reports `deployment.environment.name=test` unless you set an environment yourself; set `AUTTER_DETECT_TEST_ENV=false` (or `init_tracing(detect_test_env=False)`) to turn this off. An environment in `OTEL_RESOURCE_ATTRIBUTES` counts as set, so keep - `deployment.environment=production` out of the environment your tests run + `deployment.environment.name=production` out of the environment your tests run in. Autter leaves `test` out of default views and never pages on it. - Requests made through Starlette's or FastAPI's `TestClient`, or Django's test `Client` when the instrumentation records its host `testserver`, get @@ -581,7 +581,7 @@ exp, _ := otlptracehttp.New(ctx, "authorization": "Bearer " + os.Getenv("AUTTER_RUNTIME_KEY"), }), ) -// resource: service.name, service.version (release), deployment.environment +// resource: service.name, service.version (release), deployment.environment.name // errors: span.RecordError(err); span.SetStatus(codes.Error, err.Error()) ``` @@ -611,7 +611,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.autter.dev OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer ${AUTTER_RUNTIME_KEY}" OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_SERVICE_NAME=payments-api -OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment=production +OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment.name=production OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.01 ``` diff --git a/docs/WITHOUT-NPM.md b/docs/WITHOUT-NPM.md index c11ce66..b7385c5 100644 --- a/docs/WITHOUT-NPM.md +++ b/docs/WITHOUT-NPM.md @@ -32,7 +32,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.autter.dev OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer ${AUTTER_RUNTIME_KEY}" OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_SERVICE_NAME=payments-api -OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment=production +OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment.name=production OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.01 ``` diff --git a/examples/python/django/shop/observability.py b/examples/python/django/shop/observability.py index 0c28a2b..ce9a6a0 100644 --- a/examples/python/django/shop/observability.py +++ b/examples/python/django/shop/observability.py @@ -5,7 +5,7 @@ OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.autter.dev OTEL_EXPORTER_OTLP_HEADERS=x-autter-key=${AUTTER_RUNTIME_KEY} OTEL_SERVICE_NAME=shop - OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment=production + OTEL_RESOURCE_ATTRIBUTES=service.version=${GIT_SHA},deployment.environment.name=production OTEL_TRACES_SAMPLER=parentbased_traceidratio OTEL_TRACES_SAMPLER_ARG=0.1 """ diff --git a/examples/python/django/test_django_recipe.py b/examples/python/django/test_django_recipe.py index 214e6c2..4932aef 100644 --- a/examples/python/django/test_django_recipe.py +++ b/examples/python/django/test_django_recipe.py @@ -82,7 +82,7 @@ def test_unsampled_traffic_still_exports_every_error(self): self.assertIs(span["attributes"]["autter.tail_retained"], True) self.assertEqual(span["resource"]["service.name"], SERVICE) self.assertEqual(span["resource"]["service.version"], RELEASE) - self.assertEqual(span["resource"]["deployment.environment"], "test") + self.assertEqual(span["resource"]["deployment.environment.name"], "test") self.assertEqual(self.stub.trace_requests()[0]["headers"].get("x-autter-key"), TEST_KEY) # Unhandled → Django's 500: DjangoInstrumentor records it on the diff --git a/examples/python/testing/compose_e2e.py b/examples/python/testing/compose_e2e.py index cc4217e..b591b0c 100644 --- a/examples/python/testing/compose_e2e.py +++ b/examples/python/testing/compose_e2e.py @@ -47,7 +47,7 @@ def readme_env(service: str, extra: dict | None = None) -> dict: "OTEL_EXPORTER_OTLP_ENDPOINT": INGESTER, "OTEL_EXPORTER_OTLP_HEADERS": f"x-autter-key={LOCAL_DEV_KEY}", "OTEL_SERVICE_NAME": service, - "OTEL_RESOURCE_ATTRIBUTES": f"service.version={RUN},deployment.environment=development", + "OTEL_RESOURCE_ATTRIBUTES": f"service.version={RUN},deployment.environment.name=development", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", "OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_BSP_SCHEDULE_DELAY": "200", diff --git a/examples/python/testing/otlp_stub.py b/examples/python/testing/otlp_stub.py index 5b50648..e9655e1 100644 --- a/examples/python/testing/otlp_stub.py +++ b/examples/python/testing/otlp_stub.py @@ -169,7 +169,7 @@ def recipe_env(stub: OtlpStub, service: str, *, ratio: str = "0", extra: Optiona "OTEL_EXPORTER_OTLP_HEADERS": f"x-autter-key={TEST_KEY}", "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf", "OTEL_SERVICE_NAME": service, - "OTEL_RESOURCE_ATTRIBUTES": f"service.version={RELEASE},deployment.environment=test", + "OTEL_RESOURCE_ATTRIBUTES": f"service.version={RELEASE},deployment.environment.name=test", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", "OTEL_TRACES_SAMPLER_ARG": ratio, # Tests only: export quickly instead of every 5 s. diff --git a/package-lock.json b/package-lock.json index 0c6207b..171bdf6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6843,7 +6843,7 @@ }, "packages/runtime-node": { "name": "@autter/runtime-node", - "version": "1.16.1", + "version": "1.17.0", "license": "MIT", "dependencies": { "@opentelemetry/api": "~1.9.0", diff --git a/packages/otlp-ingester/README.md b/packages/otlp-ingester/README.md index 0193d5e..3491314 100644 --- a/packages/otlp-ingester/README.md +++ b/packages/otlp-ingester/README.md @@ -229,8 +229,8 @@ off by default, and the salt should be kept and rotated like any secret. ## Test traffic (1.18.0) -Test traffic is separated by setting `deployment.environment=test` in the -test run. The Python adapter and `@autter/runtime-node` do this themselves +Test traffic is separated by setting `deployment.environment.name=test` in +the test run (the deprecated `deployment.environment` is still read). The Python adapter and `@autter/runtime-node` do this themselves under a test runner from the next release; anything else sets it in `OTEL_RESOURCE_ATTRIBUTES`. The ingester never changes the environment because of what a request says about itself (its user agent, its host, its diff --git a/packages/runtime-node/package.json b/packages/runtime-node/package.json index aa6cb3d..c25fa90 100644 --- a/packages/runtime-node/package.json +++ b/packages/runtime-node/package.json @@ -1,6 +1,6 @@ { "name": "@autter/runtime-node", - "version": "1.16.1", + "version": "1.17.0", "description": "Autter Runtime for Node.js: request wide events, coded errors, operation logging, same-origin browser relay and a curated OpenTelemetry server tracker", "license": "MIT", "type": "module", diff --git a/packages/runtime-node/src/deployment.ts b/packages/runtime-node/src/deployment.ts index 45a8d24..1bd9b4f 100644 --- a/packages/runtime-node/src/deployment.ts +++ b/packages/runtime-node/src/deployment.ts @@ -118,3 +118,39 @@ export function testRunnerDetected(env: Env = process.env): boolean { export function resolveEnvironment(environment: string | undefined, env: Env = process.env): string { return environment ?? env.NODE_ENV ?? (testRunnerDetected(env) ? "test" : "production"); } + +/** OpenTelemetry's resource attribute for the environment (semantic conventions 1.27+). */ +export const ENVIRONMENT_ATTRIBUTE = "deployment.environment.name"; +/** The deprecated name it replaced; still read where a user sets it. */ +export const LEGACY_ENVIRONMENT_ATTRIBUTE = "deployment.environment"; + +/** + * The environment a user set in `OTEL_RESOURCE_ATTRIBUTES` (comma-separated + * `key=value`, values percent-encoded per the OpenTelemetry spec): + * `deployment.environment.name`, else the deprecated `deployment.environment`. + * Undefined when neither is set. + * + * The NodeSDK merges those attributes over the SDK's own resource, so a value + * set there has always been the environment spans report. Now that the SDK + * sends `deployment.environment.name`, a value under the old name would sit + * beside it and lose (the ingester prefers the new name); the SDK sends it + * under the new name instead, so it keeps winning. + */ +export function environmentFromResourceAttributes(env: Env = process.env): string | undefined { + const raw = env.OTEL_RESOURCE_ATTRIBUTES; + if (!raw) return undefined; + const pairs = new Map(); + for (const part of raw.split(",")) { + const at = part.indexOf("="); + if (at <= 0) continue; + const key = part.slice(0, at).trim(); + let value = part.slice(at + 1).trim(); + try { + value = decodeURIComponent(value); + } catch { + // Not percent-encoded as the spec asks: kept as written. + } + if (key && value) pairs.set(key, value); + } + return pairs.get(ENVIRONMENT_ATTRIBUTE) ?? pairs.get(LEGACY_ENVIRONMENT_ATTRIBUTE); +} diff --git a/packages/runtime-node/src/server.ts b/packages/runtime-node/src/server.ts index 46c4a72..dececa2 100644 --- a/packages/runtime-node/src/server.ts +++ b/packages/runtime-node/src/server.ts @@ -66,7 +66,7 @@ import { authHeaders, resolveIngestKey, warnKeyKind, warnMissingKey } from "./in import { IngestMetricExporter, IngestSpanExporter } from "./ingest-exporters.js"; import { makeUrlQueryPolicy } from "./url-query.js"; import { startMemoryMetrics } from "./memory.js"; -import { detectCommit, resolveEnvironment, resolveRelease } from "./deployment.js"; +import { detectCommit, ENVIRONMENT_ATTRIBUTE, environmentFromResourceAttributes, resolveEnvironment, resolveRelease } from "./deployment.js"; import { configureExportErrors, exportErrorMark, @@ -1385,7 +1385,10 @@ export function initAutterServer(options: AutterServerOptions): AutterServer { "service.instance.id": (options.instanceId || process.env.AUTTER_RUNTIME_INSTANCE_ID || randomUUID()).slice(0, 128), ...(release ? { [ATTR_SERVICE_VERSION]: release } : {}), ...(commit ? { "deployment.commit": commit } : {}), - "deployment.environment": environment, + // The current semantic-conventions name (log records already used it). A + // value set in OTEL_RESOURCE_ATTRIBUTES, under either name, still wins: + // the NodeSDK merges those over this resource. + [ENVIRONMENT_ATTRIBUTE]: environmentFromResourceAttributes() ?? environment, // OTel semconv for SDK distributions: the ingester records which // Autter SDK version each service runs (version compatibility checks). "telemetry.distro.name": distro.name, diff --git a/packages/runtime-node/src/verify.ts b/packages/runtime-node/src/verify.ts index 3c8cbb8..a1d0746 100644 --- a/packages/runtime-node/src/verify.ts +++ b/packages/runtime-node/src/verify.ts @@ -101,7 +101,7 @@ interface TestResource { function resourceAttributes(opts: TestResource) { return [ str("service.name", opts.service), - str("deployment.environment", opts.environment), + str("deployment.environment.name", opts.environment), ...(opts.release ? [str("service.version", opts.release)] : []), ...(opts.commit ? [str("deployment.commit", opts.commit)] : []), str("autter.verify.id", opts.traceId), diff --git a/packages/runtime-node/test/environment.test.mjs b/packages/runtime-node/test/environment.test.mjs index a55ec59..0c17006 100644 --- a/packages/runtime-node/test/environment.test.mjs +++ b/packages/runtime-node/test/environment.test.mjs @@ -4,7 +4,10 @@ // // - environment: the option, else NODE_ENV, else `test` when a test runner // is detected (JEST_WORKER_ID, VITEST, NODE_TEST_CONTEXT), else -// `production`. An explicit value always wins. +// `production`. An explicit value always wins. Sent as +// `deployment.environment.name`; on spans, a value the user set in +// OTEL_RESOURCE_ATTRIBUTES (under that name or the deprecated +// `deployment.environment`) wins, as the NodeSDK merges those over it. // - commit: the first commit variable (COMMIT_ENV_VARS) holding 7-40 // hexadecimal characters, sent as the resource attribute // `deployment.commit` whenever one is found. Never read from git. @@ -32,6 +35,7 @@ const { defaultRelease, detectCommit, detectCommitFrom, + environmentFromResourceAttributes, resolveEnvironment, resolveRelease, } = await tsImport("../src/deployment.ts", import.meta.url); @@ -56,6 +60,18 @@ test("environment: an explicit option wins, then NODE_ENV, then test under a run assert.deepEqual([...TEST_RUNNER_ENV_VARS], ["JEST_WORKER_ID", "VITEST", "NODE_TEST_CONTEXT"]); }); +test("environment from OTEL_RESOURCE_ATTRIBUTES: the current name, else the deprecated one", () => { + const from = (value) => environmentFromResourceAttributes(value === undefined ? {} : { OTEL_RESOURCE_ATTRIBUTES: value }); + assert.equal(from(undefined), undefined); + assert.equal(from("service.version=abc"), undefined); + assert.equal(from("deployment.environment=staging"), "staging"); + assert.equal(from("deployment.environment.name=preview"), "preview"); + assert.equal(from("deployment.environment=staging,deployment.environment.name=preview"), "preview", "the current name wins"); + assert.equal(from(" service.version = v1 , deployment.environment = eu%20west "), "eu west", "trimmed and percent-decoded"); + assert.equal(from("deployment.environment="), undefined, "empty is not set"); + assert.equal(from("deployment.environment=%E0%A4"), "%E0%A4", "a value that is not valid percent-encoding is kept as written"); +}); + test("commit: only 7 to 40 hexadecimal characters, first valid variable in the shared order", () => { // Autter's own, then the source-map CLI's four in its order, then the rest. assert.deepEqual([...COMMIT_ENV_VARS], [ @@ -125,7 +141,7 @@ test("enrichDeployment: deployment.commit only for a commit, from the shared lis // ------------------------------------------------- what the SDK sends /** Every variable the rules read, removed from each child's environment. */ -const RULE_VARS = [...TEST_RUNNER_ENV_VARS, ...COMMIT_ENV_VARS, "NODE_ENV", "AUTTER_RELEASE", "AUTTER_DETECT_RELEASE"]; +const RULE_VARS = [...TEST_RUNNER_ENV_VARS, ...COMMIT_ENV_VARS, "NODE_ENV", "AUTTER_RELEASE", "AUTTER_DETECT_RELEASE", "OTEL_RESOURCE_ATTRIBUTES"]; const received = []; let collector; @@ -158,19 +174,23 @@ after(async () => { const value = (v) => v?.stringValue ?? v?.intValue ?? v?.boolValue ?? v?.doubleValue; const attrs = (list) => Object.fromEntries((list ?? []).map((a) => [a.key, value(a.value)])); -/** The resources one service sent: of its spans, and of its log records. */ +/** + * The resources one service sent: of its spans, and of its log records. Both + * name the environment `deployment.environment.name`; it is read from there + * into `environment`. `deployment.environment` is left as sent (only a value + * the user set in OTEL_RESOURCE_ATTRIBUTES). + */ function resourcesOf(service) { const spans = []; const logs = []; for (const { body } of received) { for (const rs of body.resourceSpans ?? []) { - const resource = attrs(rs.resource?.attributes); - if (resource["service.name"] === service) spans.push(resource); + const { "deployment.environment.name": environment, ...resource } = attrs(rs.resource?.attributes); + if (resource["service.name"] === service) spans.push({ ...resource, environment }); } for (const rl of body.resourceLogs ?? []) { - // Log records name it with the newer semconv key. const { "deployment.environment.name": environment, ...resource } = attrs(rl.resource?.attributes); - if (resource["service.name"] === service) logs.push({ ...resource, "deployment.environment": environment }); + if (resource["service.name"] === service) logs.push({ ...resource, environment }); } } return { spans, logs }; @@ -236,20 +256,32 @@ function only(resources, key) { test("initAutterServer: production outside a test runner, test under one, explicit values win", async () => { const outside = await run("server"); - assert.equal(only(outside.spans, "deployment.environment"), "production"); - assert.equal(only(outside.logs, "deployment.environment"), "production"); + assert.equal(only(outside.spans, "environment"), "production"); + assert.equal(only(outside.logs, "environment"), "production"); assert.equal(only(outside.spans, "service.version"), undefined); assert.equal(only(outside.spans, "deployment.commit"), undefined); const nodeTest = await run("server", {}, { NODE_TEST_CONTEXT: "child" }); - assert.equal(only(nodeTest.spans, "deployment.environment"), "test"); - assert.equal(only(nodeTest.logs, "deployment.environment"), "test"); + assert.equal(only(nodeTest.spans, "environment"), "test"); + assert.equal(only(nodeTest.logs, "environment"), "test"); const jest = await run("server", {}, { JEST_WORKER_ID: "1", NODE_ENV: "staging" }); - assert.equal(only(jest.spans, "deployment.environment"), "staging", "NODE_ENV wins over the runner"); + assert.equal(only(jest.spans, "environment"), "staging", "NODE_ENV wins over the runner"); const vitest = await run("server", { environment: "production" }, { VITEST: "true" }); - assert.equal(only(vitest.spans, "deployment.environment"), "production", "the option wins over the runner"); + assert.equal(only(vitest.spans, "environment"), "production", "the option wins over the runner"); + + // Spans carry only the current semantic-conventions name. + assert.equal(only(outside.spans, "deployment.environment"), undefined, "no deprecated deployment.environment"); + + // A value set in OTEL_RESOURCE_ATTRIBUTES has always won on spans (the + // NodeSDK merges it over the SDK's resource); under the deprecated name it + // still does, sent as deployment.environment.name. + const legacy = await run("server", {}, { OTEL_RESOURCE_ATTRIBUTES: "deployment.environment=staging", NODE_ENV: "development" }); + assert.equal(only(legacy.spans, "environment"), "staging", "the deprecated name set by the user wins"); + assert.equal(only(legacy.spans, "deployment.environment"), "staging", "and is passed through as the user set it"); + const current = await run("server", { environment: "eu" }, { OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=preview" }); + assert.equal(only(current.spans, "environment"), "preview"); }); test("initAutterServer: the detected commit is deployment.commit and, by default, the release", async () => { @@ -284,17 +316,17 @@ test("initAutterServer: the detected commit is deployment.commit and, by default test("initAutterLogging: the same environment and release defaults", async () => { const outside = await run("logging"); - assert.equal(only(outside.logs, "deployment.environment"), "production"); + assert.equal(only(outside.logs, "environment"), "production"); assert.equal(only(outside.logs, "service.version"), undefined); assert.equal(only(outside.logs, "deployment.commit"), undefined); const vitest = await run("logging", {}, { VITEST: "true", RAILWAY_GIT_COMMIT_SHA: SHA }); - assert.equal(only(vitest.logs, "deployment.environment"), "test"); + assert.equal(only(vitest.logs, "environment"), "test"); assert.equal(only(vitest.logs, "service.version"), SHA); assert.equal(only(vitest.logs, "deployment.commit"), SHA, "logger-only mode sends the commit too"); const explicit = await run("logging", { environment: "eu", release: "v3" }, { VITEST: "true", GIT_SHA: SHA, NODE_ENV: "development" }); - assert.equal(only(explicit.logs, "deployment.environment"), "eu"); + assert.equal(only(explicit.logs, "environment"), "eu"); assert.equal(only(explicit.logs, "service.version"), "v3"); const off = await run("logging", { release: false }, { GIT_SHA: SHA });