Repository navigation
feat: removing vtex/diagnostics-nodejs - #3389
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughMigrate from VTEX diagnostics-nodejs to native OpenTelemetry NodeSDK: bootstrap OTLP exporters for traces and logs, convert global client Maps to singletons, expand OTEL options typing to carry injected ChangesOpenTelemetry SDK Migration
Sequence DiagramsequenceDiagram
participant GraphQL Request Handler as req
participant CoreServer as execute()
participant RootSpan as root span
participant Resolver as ResolverTrace()
participant ResolverSpan as resolver span
req->>CoreServer: execute GraphQL
CoreServer->>RootSpan: create span graphql operation
CoreServer->>RootSpan: set active context
CoreServer->>Resolver: run resolvers in context
Resolver->>ResolverSpan: create INTERNAL span
Resolver->>ResolverSpan: set span on extracted __otelContext
Resolver->>ResolverSpan: execute resolver
alt resolve sync
Resolver-->>ResolverSpan: end() immediately
else resolve Promise
ResolverSpan->>ResolverSpan: end() on .then()
else reject Promise
ResolverSpan->>ResolverSpan: catchError() setStatus(ERROR) recordException() end()
end
Resolver-->>CoreServer: result
CoreServer->>RootSpan: end() in finally
CoreServer-->>req: { data, errors, extensions }
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
There was a problem hiding this comment.
Actionable comments posted: 14
🧹 Nitpick comments (2)
packages/core/test/server/index.test.ts (1)
21-29: ⚡ Quick winReturn a stable mock context from
setSpan().
withTraceClient()now passes the return value oftrace.setSpan()intopropagation.inject(), but this mock returnsundefined, so the test can still pass if that propagation handoff breaks.Suggested fix
vi.mock('`@faststore/diagnostics`', () => { + const mockContext = {} const mockSpan = { setStatus: vi.fn(), recordException: vi.fn(), end: vi.fn(), } return { @@ trace: { getTracer: vi.fn(() => ({ startSpan: vi.fn(() => mockSpan), })), - setSpan: vi.fn(), + setSpan: vi.fn(() => mockContext), },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/test/server/index.test.ts` around lines 21 - 29, The mock for trace.setSpan used in tests should return a stable context object so withTraceClient() passes a real value into propagation.inject(); update the mock implementation referenced as setSpan (and any usages in withTraceClient() test setup) to return a consistent object (e.g., an empty context {} or a named mockContext) and ensure propagation.inject is called with that returned object instead of undefined.packages/diagnostics/configs/prod.json (1)
4-8: Watch the production ingest/cost impact of the new default sampling rate.Moving the default trace rate from 1% to 30% is a big observability-volume jump. I’d want dashboards/alerts on exporter failures, queue pressure, and ingest cost before rolling this out broadly.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/diagnostics/configs/prod.json` around lines 4 - 8, The prod config raised the global sampling from 1% to 30% (defaultRate and the "trace_all" rule's sampleRate both set to 0.3), which will massively increase ingest/cost; revert defaultRate and the "trace_all" sampleRate back to 0.01 (1%) or gate the 0.3 change behind a feature flag/gradual rollout, and add instrumentation and alerts for exporter failures, queue pressure, and ingest cost before enabling the higher rate cluster-wide; ensure the fix updates the JSON entries for "defaultRate" and the rule named "trace_all" and document the rollout plan.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/api/src/observability/telemetry.ts`:
- Around line 39-48: The extracted OTEL context built with
OTELAPI.propagation.extract and the span set via OTELAPI.trace.setSpan is not
activated before invoking the resolver, so calls to fn(...) still run in the
previous active context; wrap the resolver invocation in
OTELAPI.context.with(theExtractedContext, () => fn(source, vars, graphqlContext,
info)) (using the same span/context you created) to activate the new context for
downstream spans and return its result, ensuring errors are propagated out of
the context wrapper.
- Around line 47-58: The span is ending before async resolvers finish because
the code returns fn(...) directly; change the try block in telemetry wrapper so
you await the resolver result instead of returning it immediately: replace the
direct "return fn(source, vars, graphqlContext, info)" with something like
"const result = fn(source, vars, graphqlContext, info); const awaited = await
result; return awaited" (or simply "return await fn(...)") so the finally block
(span?.end()) runs only after async resolvers settle; update in the function
that references fn, span, and resolverName in telemetry.ts.
In `@packages/api/src/platforms/vtex/index.ts`:
- Around line 43-45: GraphqlVtexContextFactory is crashing because
OTELAPI.propagation.extract is dereferencing options.OTEL.__otelContext even
when options.OTEL is undefined; update the call site (where withTraceClient
supplies options) or inside GraphqlVtexContextFactory to guard extraction: if
options.OTEL is present use
OTELAPI.propagation.extract(OTELAPI.context.active(),
options.OTEL.__otelContext) otherwise call OTELAPI.propagation.extract with an
empty carrier (e.g., {}) so the non-instrumented path remains intact and tests
using plain Options continue to work. Ensure you modify the logic around
OTELAPI.propagation.extract and references to options.OTEL.__otelContext and
validate behavior in GraphqlVtexContextFactory and withTraceClient.
In `@packages/api/src/typings/globals.ts`:
- Line 21: The OTEL field on the Options type was widened to Record<string,
any>, losing the specific shape used elsewhere; restore a precise, optional OTEL
interface (e.g., declare an OTEL?: { __otelContext?: unknown; /* add only needed
fields */ } ) instead of Record<string, any>, and keep any defaulting/mandatory
logic in the options construction code (where Options instances are created) so
callers can rely on options.OTEL.__otelContext without casting; update the
Options type declaration (the OTEL symbol) and ensure the constructor or factory
that builds Options supplies defaults/validation for OTEL rather than broadening
the global type.
In `@packages/core/discovery.config.default.js`:
- Around line 166-170: The default config removed analytics.otelEnabled but
instrumentation initialization in instrumentation.ts still checks
config.analytics.otelEnabled === true; restore alignment by reintroducing
analytics.otelEnabled (set to true or the intended default) in the default
config object so the OTEL bootstrap guard in instrumentation.ts continues to
behave as expected, or alternatively update the guard in the initialize/boot
logic in instrumentation.ts to use the new runtime gate (e.g., check the new
feature flag or environment-derived value) and remove reliance on
analytics.otelEnabled; reference the analytics.otelEnabled key and the
initialization guard in instrumentation.ts when making the change.
In `@packages/core/next.config.js`:
- Line 17: The startup log currently prints a hardcoded "Analytics Enabled:
true" which can be false at runtime; update the log to reflect the actual
analytics flag by using the configuration value
(storeConfig.analytics?.otelEnabled or a derived const like analyticsEnabled)
instead of the literal true so the build output matches runtime telemetry state
and aids debugging.
In `@packages/core/src/server/options.ts`:
- Around line 55-68: Move OTEL setup (OTELAPI.trace.getTracer, tracer.startSpan,
OTELAPI.trace.setSpan and OTELAPI.propagation.inject) into the try block and
initialize the span variable to undefined before the try so the catch/finally
can always reference it; specifically, declare let span: ReturnType<typeof
tracer.startSpan> | undefined (or appropriate type) before the try, then inside
the try call getTracer(), startSpan(), setSpan(...) and inject(...), and return
options as T, while the catch uses span?.setStatus and span?.recordException and
the finally always calls span?.end().
- Around line 47-53: In withTraceClient update the options object to preserve
existing apiOptions.OTEL fields instead of overwriting them (merge
apiOptions.OTEL into OTEL so apiOptions.OTEL.enabled and other properties are
retained) and move the OTEL setup (calls to getTracer, startSpan, setSpan,
inject) inside the try block so any setup errors are caught and ensure the
finally block always ends/cleans the span; reference the options constant and
the functions getTracer, startSpan, setSpan, inject, and the try/catch/finally
surrounding the return.
In `@packages/diagnostics/`@types/global.d.ts:
- Around line 3-12: The global declaration still imports LogClient from the
removed `@vtex/diagnostics-nodejs` and declares TELEMETRY_CLIENT / TRACE_CLIENT
types that no longer match start.ts (which stores an OpenTelemetry SDK
instance). Remove the import line and update the types in the fsDiagnostics
global to match the actual runtime types used in
packages/diagnostics/src/start.ts (e.g., set TELEMETRY_CLIENT to the
OpenTelemetry SDK type you instantiate there — or use a conservative
unknown/any/NodeSDK type if you don’t want to add a new dependency — and replace
TRACE_CLIENT/LOGGER_CLIENT with the corresponding OpenTelemetry/opaque types or
undefined). Ensure you reference and mirror the exact symbol used in start.ts
for TELEMETRY_CLIENT and stop importing LogClient.
In `@packages/diagnostics/package.json`:
- Around line 24-27: The package-level "types" field is out of sync with the
exports map; update the package.json "types" entry (the top-level "types" key)
to point to "./dist/index.d.ts" so it matches exports["."].types, ensuring both
consumers using the export map and tools reading package.json resolve the same
declaration file.
- Around line 33-43: The package.json contains pinned versions for several
shared deps ("`@grpc/grpc-js`", "`@opentelemetry/api`", "`@opentelemetry/api-logs`",
"`@opentelemetry/exporter-logs-otlp-grpc`",
"`@opentelemetry/exporter-trace-otlp-grpc`",
"`@opentelemetry/instrumentation-http`", "`@opentelemetry/resources`",
"`@opentelemetry/sdk-logs`", "`@opentelemetry/sdk-node`",
"`@opentelemetry/sdk-trace-node`", "`@vtex/diagnostics-semconv`") — move each of
these entries into the workspace catalog in pnpm-workspace.yaml (or the repo’s
catalog file) with the desired version, then replace the inline versions in this
package.json with catalog references (e.g. "catalog:") so the package.json uses
the catalog alias for each dependency.
In `@packages/diagnostics/src/logger.ts`:
- Around line 24-37: setupLogs() currently constructs a LoggerProvider (new
LoggerProvider(...)) and installs it via
logs.setGlobalLoggerProvider(loggerProvider) but never returns or exposes it, so
its buffered BatchLogRecordProcessor can be dropped on exit; modify setupLogs()
to return the created loggerProvider (or a dedicated async shutdown function)
and update the SIGTERM handler in start.ts to await loggerProvider.shutdown()
(alongside awaiting sdk.shutdown()) so buffered log records are flushed before
process exit; reference symbols: setupLogs(), LoggerProvider,
BatchLogRecordProcessor, logs.setGlobalLoggerProvider,
loggerProvider.shutdown(), and the SIGTERM handler that calls sdk.shutdown().
In `@packages/diagnostics/src/start.ts`:
- Around line 18-24: The resource built by resourceFromAttributes is missing the
OTel "service.name" attribute; include the bootstrap's serviceName into that
attributes object (e.g., add ['service.name']: serviceName ?? opt.serviceName ??
'unknown_service') so the resource created in the resourceFromAttributes call
contains the proper service identifier; update the resource construction in
start.ts (the resourceFromAttributes invocation) to include this key while
keeping existing attributes like ATTR_VTEX_ACCOUNT_NAME unchanged.
- Around line 36-48: Move the assignment to the cached singleton so it only
happens after sdk.start() completes successfully: don't set
global.fsDiagnostics.TELEMETRY_CLIENT before calling sdk.start(); call
sdk.start(), let it complete (catch synchronous throws), and only then assign
global.fsDiagnostics.TELEMETRY_CLIENT = sdk so a thrown error from sdk.start()
won't leave a broken singleton; update the shutdown handler to reference the
cached TELEMETRY_CLIENT (or sdk) as appropriate and ensure exceptions from
sdk.start() are propagated/handled without mutating
global.fsDiagnostics.TELEMETRY_CLIENT.
---
Nitpick comments:
In `@packages/core/test/server/index.test.ts`:
- Around line 21-29: The mock for trace.setSpan used in tests should return a
stable context object so withTraceClient() passes a real value into
propagation.inject(); update the mock implementation referenced as setSpan (and
any usages in withTraceClient() test setup) to return a consistent object (e.g.,
an empty context {} or a named mockContext) and ensure propagation.inject is
called with that returned object instead of undefined.
In `@packages/diagnostics/configs/prod.json`:
- Around line 4-8: The prod config raised the global sampling from 1% to 30%
(defaultRate and the "trace_all" rule's sampleRate both set to 0.3), which will
massively increase ingest/cost; revert defaultRate and the "trace_all"
sampleRate back to 0.01 (1%) or gate the 0.3 change behind a feature
flag/gradual rollout, and add instrumentation and alerts for exporter failures,
queue pressure, and ingest cost before enabling the higher rate cluster-wide;
ensure the fix updates the JSON entries for "defaultRate" and the rule named
"trace_all" and document the rollout plan.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b406e425-b6fd-425a-a705-f929ee67ea90
⛔ Files ignored due to path filters (2)
docs/observability.mdis excluded by none and included by nonepnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (17)
packages/api/src/observability/telemetry.tspackages/api/src/platforms/vtex/index.tspackages/api/src/typings/globals.tspackages/core/discovery.config.default.jspackages/core/next.config.jspackages/core/src/instrumentation.tspackages/core/src/server/options.tspackages/core/test/server/index.test.tspackages/diagnostics/@types/global.d.tspackages/diagnostics/configs/prod.jsonpackages/diagnostics/package.jsonpackages/diagnostics/src/globals.tspackages/diagnostics/src/index.tspackages/diagnostics/src/logger.tspackages/diagnostics/src/start.tspackages/diagnostics/src/tracer.tspackages/diagnostics/vite.config.mts
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/instrumentation.ts (1)
5-17:⚠️ Potential issue | 🔴 CriticalRestore analytics.otelEnabled opt-out for OTEL bootstrap in Next instrumentation
packages/core/src/instrumentation.tsregister()initializes telemetry wheneverprocess.env.NEXT_RUNTIME === 'nodejs', callinggetTelemetryClient(...)without checkingconfig.analytics?.otelEnabled.packages/diagnostics/src/start.tsgetTelemetryClient()starts theNodeSDKviasdk.start()unconditionally (aside from reusing an existing global client).- Repo-wide usage of
otelEnabledis limited topackages/core/src/server/options.ts(apiOptions.OTEL.enabled) and docs, soanalytics.otelEnabled: falseappears to be bypassed for the Next.js instrumentation hook.
Action: reintroduce gating inregister()(or ensure@faststore/diagnosticsrespects an enabled flag) so the opt-out contract matches configuration/docs.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/instrumentation.ts` around lines 5 - 17, In register() in instrumentation.ts, avoid unconditionally calling getTelemetryClient(...) when NEXT_RUNTIME==='nodejs'; instead gate the telemetry bootstrap with the analytics opt-out by checking config.analytics?.otelEnabled (treat undefined as enabled, but respect false) before importing/calling getTelemetryClient, or alternatively pass an explicit enabled flag through to getTelemetryClient so packages/diagnostics (start.ts / NodeSDK start) can no-op when otel is disabled; update the conditional around the import/return that currently calls getTelemetryClient to honor config.analytics?.otelEnabled.
♻️ Duplicate comments (1)
packages/api/src/observability/telemetry.ts (1)
54-74:⚠️ Potential issue | 🟠 Major | ⚡ Quick winEnd resolver spans on rejection and sync throw paths.
The resolver span is closed on success but not on error, so rejected async resolvers and thrown sync resolvers leave spans open.
Suggested fix
if (returnedValue instanceof Promise) { return returnedValue - .then((promisedResult) => { - span?.end() - - return promisedResult - }) + .then((promisedResult) => promisedResult) .catch((err) => { throw catchError( err, span, resolverName ?? 'Unknown Graphql Resolver' ) + }) + .finally(() => { + span?.end() }) as TReturn } span?.end() return returnedValue } catch (error: any) { - throw catchError(error, span, resolverName) + const handled = catchError(error, span, resolverName) + span?.end() + throw handled }#!/bin/bash set -euo pipefail rg -n -C4 'returnedValue instanceof Promise|catchError\\(|span\\?\\.end\\(|\\.finally\\(' packages/api/src/observability/telemetry.tsExpected result: every resolver execution path (sync success, sync throw, async resolve, async reject) should include one span end.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/api/src/observability/telemetry.ts` around lines 54 - 74, The resolver span isn't ended on error paths: add span?.end() before rethrowing in both the async rejection and sync throw paths so every execution ends the span; specifically, update the Promise branch around returnedValue (either call span?.end() in the .catch before calling throw catchError(...) or replace the .then/.catch with .finally to call span?.end()) and ensure the outer catch block that catches synchronous throws calls span?.end() before throwing catchError(error, resolverName). Reference returnedValue, span, catchError, and resolverName when making the changes.
🧹 Nitpick comments (1)
packages/api/test/unit/platforms/vtex/clients/commerce.test.ts (1)
18-19: ⚡ Quick winUse an explicit OTEL fixture shape in this unit test.
OTEL: {}is too loose versus runtime wiring and can hide contract-shape regressions in context factories.Suggested refactor
- OTEL: {}, + OTEL: { + enabled: false, + __otelContext: {}, + },As per coding guidelines, for
packages/**/*.{ts,tsx}: "Ensure type safety and avoid type assertions when possible."🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/api/test/unit/platforms/vtex/clients/commerce.test.ts` around lines 18 - 19, The test uses a loose OTEL: {} fixture which can hide contract regressions; update the test to construct an explicit OTEL fixture matching the runtime shape and type rather than an empty object or unsafe assertion. Import or reference the Options/type used by the code under test and replace OTEL: {} with a well-typed object containing the expected OTEL properties (e.g., the fields the context factory expects), ensuring the fixture aligns with the Options interface and removing the need for a broad type assertion.Sources: Coding guidelines, Pipeline failures
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@packages/core/src/instrumentation.ts`:
- Around line 5-17: In register() in instrumentation.ts, avoid unconditionally
calling getTelemetryClient(...) when NEXT_RUNTIME==='nodejs'; instead gate the
telemetry bootstrap with the analytics opt-out by checking
config.analytics?.otelEnabled (treat undefined as enabled, but respect false)
before importing/calling getTelemetryClient, or alternatively pass an explicit
enabled flag through to getTelemetryClient so packages/diagnostics (start.ts /
NodeSDK start) can no-op when otel is disabled; update the conditional around
the import/return that currently calls getTelemetryClient to honor
config.analytics?.otelEnabled.
---
Duplicate comments:
In `@packages/api/src/observability/telemetry.ts`:
- Around line 54-74: The resolver span isn't ended on error paths: add
span?.end() before rethrowing in both the async rejection and sync throw paths
so every execution ends the span; specifically, update the Promise branch around
returnedValue (either call span?.end() in the .catch before calling throw
catchError(...) or replace the .then/.catch with .finally to call span?.end())
and ensure the outer catch block that catches synchronous throws calls
span?.end() before throwing catchError(error, resolverName). Reference
returnedValue, span, catchError, and resolverName when making the changes.
---
Nitpick comments:
In `@packages/api/test/unit/platforms/vtex/clients/commerce.test.ts`:
- Around line 18-19: The test uses a loose OTEL: {} fixture which can hide
contract regressions; update the test to construct an explicit OTEL fixture
matching the runtime shape and type rather than an empty object or unsafe
assertion. Import or reference the Options/type used by the code under test and
replace OTEL: {} with a well-typed object containing the expected OTEL
properties (e.g., the fields the context factory expects), ensuring the fixture
aligns with the Options interface and removing the need for a broad type
assertion.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3c31f678-0cbe-4558-8dee-c5674b02dd63
📒 Files selected for processing (6)
packages/api/src/observability/telemetry.tspackages/api/test/unit/platforms/vtex/clients/commerce.test.tspackages/core/src/instrumentation.tspackages/diagnostics/package.jsonpackages/diagnostics/src/logger.tspackages/diagnostics/src/start.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/diagnostics/src/logger.ts
- packages/diagnostics/src/start.ts
- packages/diagnostics/package.json
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/api/test/integration/mutations.test.ts`:
- Line 27: The test adds a new showSponsored field that looks unrelated to the
OpenTelemetry migration; either remove this field from the test to keep the PR
focused, or if it is intentional, update the Options shape/type (e.g., the
Options interface/contract used by your mutations and fixtures) and all
callers/mocks (tests that construct Options in mutations.test.ts and any
factories) to include showSponsored, adjust affected tests, and add a note in
the PR description explaining the intentional contract change so reviewers know
it’s deliberate rather than incidental.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 2bebabbe-d4c7-493f-bfcf-045474bf0211
📒 Files selected for processing (3)
packages/api/test/integration/mutations.test.tspackages/api/test/integration/queries.test.tspackages/api/test/mocks/ValidateCartMutation.ts
✅ Files skipped from review due to trivial changes (2)
- packages/api/test/integration/queries.test.ts
- packages/api/test/mocks/ValidateCartMutation.ts
renatomaurovtex
left a comment
There was a problem hiding this comment.
Review — feat: removing vtex/diagnostics-nodejs
Migrating @faststore/diagnostics off @vtex/diagnostics-nodejs onto raw OpenTelemetry SDKs. You own this area, so the architecture direction isn't in question — flagging the concrete things that look like they'd bite on build/behavior. The body reads like a spike ("Testing OTEL…"); calling that out in case this isn't meant to merge as-is. Reviewed everything except pnpm-lock.yaml.
🔴 build/types packages/diagnostics/@types/global.d.ts still imports from the removed package
package.json drops @vtex/diagnostics-nodejs from dependencies, but the global type still imports deep paths from it:
import type { TelemetryClient } from '@vtex/diagnostics-nodejs/dist/telemetry/client.js'
import type { TraceClient } from '@vtex/diagnostics-nodejs/dist/types/traces.js'
import type { LogClient } from '@vtex/diagnostics-nodejs/dist/types/logs.d.ts'With the dep gone these imports resolve only by accident (transitive hoist) and break tsc otherwise. On top of that the declared shapes no longer match what's assigned at runtime:
TELEMETRY_CLIENT: TelemetryClient← assigned aNodeSDK(start.ts)LOGGER_CLIENT: LogClient← assigned aLoggerProvider(logger.ts)TRACE_CLIENT: TraceClient← never assigned anymore
Suggest retyping the global to the actual OTEL types you now store (NodeSDK, LoggerProvider) and dropping the dead TRACE_CLIENT.
🔴 deps New runtime deps on a published package need the discipline checklist + sign-off
@faststore/diagnostics is published (4.3.0-dev.2, no private: true, ships dist). This adds 8 runtime deps (@grpc/grpc-js, @opentelemetry/sdk-node, sdk-logs, sdk-trace-node, exporter-*-otlp-grpc, api-logs, resources) and swaps @vtex/diagnostics-nodejs→@vtex/diagnostics-semconv. Per Dependency Discipline these need bucket/justification/bundle-impact recorded and explicit human approval in the PR description. Shared versions should come from catalog: in pnpm-workspace.yaml rather than fresh ^ ranges — note the OTEL set is also version-skewed (api-logs/exporter-* on 0.219.0, sdk-trace-node/resources on 2.8.0).
🟠 behavior OTEL opt-out is removed — telemetry is now always-on
instrumentation.ts drops the config.analytics.otelEnabled === true gate, next.config.js hardcodes Analytics Enabled: true, and otelEnabled is removed from discovery.config.default.js. Combined with the hardcoded *.vtex.systems collector endpoints in globals.ts, every FastStore store (this is MIT/open-source) now ships traces+logs to VTEX collectors with no way to disable it. Is removing the toggle intentional? At minimum this deserves a release note.
🟠 bug withTraceClient try/catch wraps a no-op and can return undefined
const context = OTELAPI.trace.setSpan(OTELAPI.context.active(), span)
OTELAPI.propagation.inject(context, options.OTEL.__otelContext) // real work, OUTSIDE try
try {
return options as T // nothing here can throw
} catch (error) { // dead branch — and it doesn't return,
span?.setStatus(...) // so on a (impossible) throw the fn returns undefined,
span?.recordException(error) // violating Promise<T>
} finally {
span?.end() // span ends immediately around a bare return
}The span starts and ends around a return statement, so it traces nothing and the child resolver spans (extracted via propagation) attach to an already-ended parent. If the intent is a parent span over the GraphQL execution, the inject + the actual execution need to be inside the traced scope; otherwise drop the try/catch and just return options.
🟡 type OTEL public type loosened to Record<string, any>
packages/api/src/typings/globals.ts changes the typed OTEL?: { enabled; traceparent?; tracestate? } to OTEL: Record<string, any> (also now required). That's a public Options contract change and an any regression — downstream callers lose all type safety on OTEL. Consider a named interface ({ __otelContext: Record<string, unknown>; enabled?: boolean }).
🟡 nit compression: 'gzip' as any in tracer.ts — cast hides a typing gap; prefer the exporter's CompressionAlgorithm enum.
💬 config prod sampling bumped 0.01 → 0.3 (30×)
configs/prod.json raises defaultRate 30×. Just confirming that trace-volume/cost jump is intended for prod.
💬 scope Unrelated showSponsored changes in the diff?
test/integration/mutations.test.ts gains showSponsored: false and test/mocks/ValidateCartMutation.ts adds showSponsored=false to the IS URL — these look unrelated to the OTEL migration. Should they be in this PR?
Verdict: Changes requested
Blocking (🔴/🟠):
@types/global.d.tsimports a removed package and its declared types no longer match the assigned values — retype to the OTEL types you now store.- Published-package runtime dep swap needs the Dependency Discipline checklist + explicit human sign-off; align versions via
catalog:. - Confirm the removal of the OTEL opt-out (always-on telemetry to VTEX collectors) is intentional; release-note it.
withTraceClienttry/catch wraps a no-op and can returnundefined— fix the traced scope or drop the wrapper.
Non-blocking (🟡/💬):
OTEL: Record<string, any>public-type regression.'gzip' as anycast.- Confirm the 30× prod sampling bump.
- Drop the unrelated
showSponsoredtest changes (or explain why they belong here).
Checks to confirm before merge: pnpm lint · build (tsc on diagnostics/api/core) · pnpm turbo run test --filter=@faststore/api --filter=@faststore/core · pnpm size.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/server/index.ts`:
- Around line 138-151: The type assertion in the destructuring of the result
from the run() function incorrectly marks errors as a required field. Change the
type assertion from `{ data: D; errors: unknown[] }` to `{ data: D; errors?:
unknown[] }` to make the errors field optional, matching what the enveloped
GraphQL execute function can actually return. Then ensure the function's return
type contract is satisfied by defaulting errors to an empty array when it is
undefined, using the nullish coalescing operator or conditional logic when
assigning to the errors field in the returned object.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: db10420d-7c33-4fad-92cb-c7a452e49615
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (6)
packages/api/src/observability/telemetry.tspackages/core/src/server/index.tspackages/core/src/server/options.tspackages/diagnostics/@types/global.d.tspackages/diagnostics/package.jsonpackages/diagnostics/src/globals.ts
💤 Files with no reviewable changes (1)
- packages/diagnostics/src/globals.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/diagnostics/src/logger.ts`:
- Around line 97-101: The ATTR_VTEX_APPLICATION_ID attribute in the attributes
object is hardcoded to 'faststore' instead of using the opt.serviceName value
like start.ts does, causing log and trace correlation issues. Replace the
hardcoded 'faststore' value for ATTR_VTEX_APPLICATION_ID with opt.serviceName to
ensure consistency across the telemetry attributes and maintain proper
correlation between logs and traces.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: afcbe222-3f45-42dd-b11b-3f3f3398446c
📒 Files selected for processing (2)
packages/diagnostics/src/logger.tspackages/diagnostics/src/start.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/diagnostics/src/start.ts
Requested new review after changes
| Root folder at: ${getRootFolder()} | ||
| AccountID: ${storeConfig.api?.storeId ?? 'Unknown'} | ||
| Analytics Enabled: ${storeConfig.analytics?.otelEnabled ?? false} | ||
| Analytics Enabled: true |
There was a problem hiding this comment.
should this be always true?
There was a problem hiding this comment.
Yes, this is the default behaviour. This shouldn't be disabled anymore after discussing with the team
|
a IA recomendou algumas coisas, vê se faz sentido ou podemos skipar:
|
Co-authored-by: Cursor <[email protected]> # Conflicts: # packages/api/src/platforms/vtex/index.ts # packages/core/src/server/index.ts
renatomaurovtex
left a comment
There was a problem hiding this comment.
Follow-up review — feat: removing vtex/diagnostics-nodejs
Re-reviewed after the 3 commits pushed today (b56804d, a198e2d, e1c088f) since my June 14 review was dismissed. Checked each blocking point from that review against the current head.
Previously 🔴/🟠, now resolved:
@types/global.d.tsno longer imports the removed package — retyped toNodeSDK, deadTRACE_CLIENT/TELEMETRY_CLIENTSmap dropped.withTraceClient(the no-op try/catch that traced nothing) is gone entirely —server/index.tsnow wraps execution in a realwithRootSpanthat's active-context-aware and only runs whenOTEL_ENABLED.- Always-on telemetry:
instrumentation.tsnow hardcodesinstrumentationEnabled = false("Disabled feature until release date"), andapiOptions.OTEL_ENABLED = false. Telemetry is fully opt-in/gated pending release rather than always-on — addresses the concern in the safer direction. Confirmed with @ommeirelles's comment that the toggle removal itself was discussed with the team. OTEL: Record<string, any>public-type regression — replaced with a typedOTEL_ENABLED?: boolean, no moreany.'gzip' as anycast — gone; compression now follows the standardOTEL_EXPORTER_OTLP_COMPRESSIONenv var.- Sensitive-data logging (flagged by @eduardoformiga's AI-assisted pass on 07-29:
JSON.stringify(request)in the OTEL logger leaking headers/cookies/tokens) — fixed ine1c088f. Currentgraphql.tsonly logsoperation.__meta__.operationName/operationHash, with an explicit comment that variables/query body are deliberately excluded. Also fixed the related "logger spams on every request even when disabled" bug:logger()now resolvesTELEMETRY_CLIENTper-call instead of capturing it at module-load time (undefined forever) — covered by a new regression test inlogger.test.ts.
Still open:
- 🟠 deps — this still adds 8 new OTEL runtime deps (
@opentelemetry/sdk-node,sdk-logs,sdk-trace-node,exporter-*-otlp-grpc,api-logs,resources,@grpc/grpc-js) to@faststore/diagnostics, a published package. Per Dependency Discipline this needs the bucket/justification/bundle-impact checklist and an explicit human sign-off recorded in the PR description — the body still just says "Testing OTEL without@vtex/diagnostics-nodejs". Given telemetry is now hard-disabled until release, this isn't merge-blocking today, but flagging so it's not missed before the flag flips on. - 🟡 SonarQube quality gate is failing: 43.10% coverage on new code (needs 75%). Rest of CI (build, FastStore, codesandbox, PR title) is green; UI Tests pending Chromatic baseline acceptance only.
- 💬
showSponsored: falseinmutations.test.tsstill looks unrelated to this PR — same note as before, not blocking.
Verdict: Approved with comments
Blocking (🔴/🟠): none for the current disabled-by-default state. Confirm before flipping the feature flag on for release: (1) Dependency Discipline sign-off recorded in the PR description for the new OTEL runtime deps, (2) new-code coverage above the Sonar gate.
Non-blocking (🟡/💬):
- SonarQube new-code coverage gate (43.10% < 75%).
- Unrelated
showSponsoredtest change.
Checks to confirm before merge: pnpm lint · build · pnpm turbo run test --filter=@faststore/diagnostics --filter=@faststore/api --filter=@faststore/core · pnpm size.
|


0 New Issues
0 Fixed Issues
0 Accepted Issues
Testing OTEL without
@vtex/diagnostics-nodejsSummary by CodeRabbit
SFS-3279
SFS-3219