package com.atlassian.bitbucket.mesh.grpc;

import com.atlassian.bitbucket.mesh.execution.ExecutionManager;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;

public class ExecutionContextServerInterceptor implements ServerInterceptor {

    private final ExecutionManager executionManager;

    public ExecutionContextServerInterceptor(ExecutionManager executionManager) {
        this.executionManager = executionManager;
    }

    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers,
                                                                 ServerCallHandler<ReqT, RespT> next) {
        return executionManager.withContext(ctx -> new ExecutionContextServerCallListener<>(
                next.startCall(call, headers),
                ctx));
    }
}
