Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Otel looses Trace Context while streaming #1428

Open
jonathangraf opened this issue Feb 17, 2025 · 2 comments · May be fixed by #1429
Open

Otel looses Trace Context while streaming #1428

jonathangraf opened this issue Feb 17, 2025 · 2 comments · May be fixed by #1429

Comments

@jonathangraf
Copy link

As stated here Otel support should implement yourself via Interceptors. But when doing so, it seems that while streaming, Otel seems to lose its Context and doesn't link the traces correctly.
Here is my implementation of it:

import { context, propagation, Span, SpanKind, trace } from '@opentelemetry/api';

import { Interceptor } from '@connectrpc/connect';

export type Carrier = { 
    traceparent?: string;
    tracestate?: string;
}

const tracer = trace.getTracer('connect-rpc');

type InterceptorResponse = Awaited<ReturnType<ReturnType<Interceptor>>>;

const handleSpanEnd = (response: InterceptorResponse, span: Span) => {
    if (!response.stream) {
        span.end();

        return response;
    }

    async function* stream() {
        if (!response.stream) {
            throw new Error('Stream is not defined');
        }

        const activeContext = context.active();

        // eslint-disable-next-line fp/no-loops
        for await (const message of response.message) {
            yield context.with(activeContext, () => message);
        }

        span.end();
    }
    
    return {
        ...response,
        message: stream(),
    };
};

export const serverInterceptor: Interceptor[] = [
    (next) => async (request) => {
        const parentContext = propagation.extract(
            context.active(),
            Object.fromEntries(request.header.entries()),
        );
        const span = tracer.startSpan(
            `${request.service.typeName}/${request.method.name}`,
            {
                kind: SpanKind.SERVER,
            },
            parentContext,
        );

        return context.with(trace.setSpan(parentContext, span), async () => {
            const activeContext = context.active();
            context.bind(activeContext, request);
            context.bind(activeContext, next);
            const response = await next(request);
            context.bind(activeContext, response);
            
            return handleSpanEnd(response, span);
        });
    },
];

export const clientInterceptor: Interceptor[] = [ 
    (next) => async (request) => {
        const span = tracer.startSpan(
            `${request.service.typeName}/${request.method.name}`, {
                kind: SpanKind.CLIENT,
            });
        const parentContext = context.active();

        return context.with(trace.setSpan(parentContext, span), async () => {
            const activeContext = context.active();
            context.bind(activeContext, request);
            const output: Carrier = {};
            propagation.inject(activeContext, output);
            Object.entries(output).forEach(([key, value]) => {
                key && value && request.header.set(key, value);
            });

            context.bind(activeContext, next);
            const response = await next(request);
            context.bind(activeContext, response);

            return handleSpanEnd(response, span);
        });      
    },
];

So the clientInterceptor should pick up on the context set by the serverInterceptor. Which works for unary requests but not for streaming requests.

@timostamm
Copy link
Member

Hey @jonathangraf, I'm not familiar with Otel. But we're missing a complete example for interceptors, so I'm adding one here: connectrpc/examples-es#2452

I noticed that while I see the request message in the client for unary and server-streaming RPCs, I don't see the request message in the server for server-streaming RPCs. We'll have to take a closer look, but this might be a bug in Connect.

@jonathangraf
Copy link
Author

@timostamm is there anything I could do to help out?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants