Repository: grpc/grpc-go
File: stats/opentelemetry/e2e_test.go (Go)

Code before:
	defer backend.Stop()

	// Dial with healthCheckConfig to trigger the internal health stream.
	sc := `{"healthCheckConfig": {"serviceName": ""}}`
	dopts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		opentelemetry.DialOption(otelOptions),
		grpc.WithDefaultServiceConfig(sc),
	}

	cc, err := grpc.NewClient(backend.Address, dopts...)
	if err != nil {
		t.Fatalf("Failed to create client: %v", err)
	}
	defer cc.Close()

	// Perform an RPC to ensure the subchannel connects and health stream initializes.
	ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
	defer cancel()
	client := testgrpc.NewTestServiceClient(cc)
	if _, err := client.EmptyCall(ctx, &testpb.Empty{}); err != nil {
		t.Fatalf("EmptyCall failed: %v", err)
	}

	// Short sleep to allow async telemetry logs (if any) to propagate.
	time.Sleep(100 * time.Millisecond)

	if tl.found() {
		t.Fatal("Unexpected OpenTelemetry error log found for health stream")
	}
}

// Minimal LoggerV2 implementation to avoid recursion and capture specific errors.
type testLogReader struct {
	mu   sync.Mutex
	seen bool
	grpclog.LoggerV2
}

func (l *testLogReader) found() bool {
	l.mu.Lock()
	defer l.mu.Unlock()
	return l.seen
}

func (l *testLogReader) Error(args ...any)                 { l.check(fmt.Sprint(args...)) }
func (l *testLogReader) Errorf(format string, args ...any) { l.check(fmt.Sprintf(format, args...)) }
func (l *testLogReader) Errorln(args ...any)               { l.check(fmt.Sprintln(args...)) }
func (l *testLogReader) Info(...any)                       {}
func (l *testLogReader) Infoln(...any)                     {}
func (l *testLogReader) Infof(string, ...any)              {}

Review comment (performance):
We should avoid adding sleeps of arbitrary durations in tests. If the duration is too short, the test becomes flaky; if it is too long, it unnecessarily slows down the CI pipeline. Instead, we should rely on channels and the deterministic sequence of events.

For example, if an RPC is successfully made, it confirms that the health client has already connected to the health server. I suspect this also implies that if the OpenTelemetry (OTel) stats handler were to be triggered, it would have already been called, making the sleep redundant.

Code after:
	defer backend.Stop()

	healthcheck.SetServingStatus("", healthpb.HealthCheckResponse_SERVING)

	// Dial with healthCheckConfig to trigger the internal health stream.
	sc := `{"loadBalancingConfig": [{"round_robin":{}}], "healthCheckConfig": {"serviceName": ""}}`
	dopts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		opentelemetry.DialOption(otelOptions),
		grpc.WithDefaultServiceConfig(sc),
	}

	cc, err := grpc.NewClient(backend.Address, dopts...)
	if err != nil {
		t.Fatalf("Failed to create client: %v", err)
	}
	defer cc.Close()

	// Perform an RPC to ensure the subchannel connects and health stream initializes.
	ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
	defer cancel()
	client := testgrpc.NewTestServiceClient(cc)
	if _, err := client.EmptyCall(ctx, &testpb.Empty{}); err != nil {
		t.Fatalf("EmptyCall failed: %v", err)
	}
}