Skip to content

In 2.x - is it possible to add metadata to a ServerReponse? Is it possible in a ServerInterceptor? #2119

@tweidema

Description

@tweidema

What are you trying to achieve?

I would like to add metadata to the response sent back to the client. Preferably in a ServerInterceptor.

What have you tried so far?

Here is my attempt, but metadata is a get-only property

struct grpcServerTracingInterceptor: ServerInterceptor {
    let logger: Logger
    init(logger: Logger) {
        self.logger = logger
    }
    func intercept<Input: Sendable, Output: Sendable>(
        request: StreamingServerRequest<Input>,
        context: ServerContext,
        next: @Sendable (
           _ request: StreamingServerRequest<Input>,
           _ context: ServerContext
        ) async throws -> StreamingServerResponse<Output>
    ) async throws -> StreamingServerResponse<Output> {
        logger.info("Pre-intercept of \(context.descriptor.service):\(context.descriptor.method)")
        let callTime = Date()
        // Forward the request.
        var response = try await next(request, context)

        logger.info("Post-intercept of \(context.descriptor.service):\(context.descriptor.method)")
        let duration = callTime.timeIntervalSinceNow
        response.metadata.addString("gRPC;dur=\(duration)", forKey: "Server-Timing")
        return response
    }
}

The addString (2nd-last line) gives: Cannot use mutating member on immutable value: 'metadata' is a get-only property

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/supportAdopter support requests.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions