xi-db commented on code in PR #54113:
URL: https://github.com/apache/spark/pull/54113#discussion_r2794654802


##########
sql/connect/server/src/main/scala/org/apache/spark/sql/connect/service/RequestDecompressionInterceptor.scala:
##########
@@ -0,0 +1,302 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql.connect.service
+
+import scala.util.control.NonFatal
+
+import io.grpc.{Context, Metadata, ServerCall, ServerCallHandler, 
ServerInterceptor}
+import io.grpc.ForwardingServerCallListener.SimpleForwardingServerCallListener
+
+import org.apache.spark.connect.proto
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys.{BYTE_SIZE, CLASS_NAME, SESSION_ID, 
USER_ID}
+import org.apache.spark.sql.connect.utils.{ErrorUtils, PlanCompressionUtils}
+
+/**
+ * Interceptor that decompresses compressed requests before they reach 
downstream handlers.
+ *
+ * This interceptor currently handles:
+ *   - ExecutePlanRequest with compressed plans
+ *   - AnalyzePlanRequest with compressed plans (Schema, Explain, TreeString, 
IsLocal,
+ *     IsStreaming, InputFiles, SemanticHash, and SameSemantics analysis types)
+ *
+ * Compressed plan size metrics are tracked in gRPC Context for use by 
handlers.
+ */
+class RequestDecompressionInterceptor extends ServerInterceptor with Logging {
+
+  override def interceptCall[ReqT, RespT](
+      call: ServerCall[ReqT, RespT],
+      headers: Metadata,
+      next: ServerCallHandler[ReqT, RespT]): ServerCall.Listener[ReqT] = {
+
+    // Create a listener that will intercept and decompress the message
+    val listener = next.startCall(call, headers)
+
+    new SimpleForwardingServerCallListener[ReqT](listener) {
+      override def onMessage(message: ReqT): Unit = {
+        message match {
+          case req: proto.ExecutePlanRequest =>
+            handleRequestWithDecompression(
+              req.getUserContext.getUserId,
+              req.getSessionId,
+              () => decompressExecutePlanRequest(req))
+
+          case req: proto.AnalyzePlanRequest =>
+            handleRequestWithDecompression(
+              req.getUserContext.getUserId,
+              req.getSessionId,
+              () => decompressAnalyzePlanRequest(req))
+
+          case other =>
+            // Forward all other message types as-is (no decompression or 
error handling needed)
+            super.onMessage(other)
+        }
+      }
+
+      private def handleRequestWithDecompression[T](
+          userId: String,
+          sessionId: String,
+          decompressRequest: () => (T, Option[Long], Option[Long])): Unit = {
+        val (decompressedReq, compressedSize, otherCompressedSize) =
+          try {
+            decompressRequest()
+          } catch {
+            case NonFatal(e) =>
+              // Handle decompression errors
+              logError(
+                log"Plan decompression failed: " +
+                  log"userId=${MDC(USER_ID, userId)}, " +
+                  log"sessionId=${MDC(SESSION_ID, sessionId)}",
+                e)
+              ErrorUtils.handleError("planDecompression", call, userId, 
sessionId)(e)
+              return
+          }
+
+        // Set compressed size(s) in context if present
+        var contextToUse = Context.current()
+        compressedSize.foreach { size =>
+          contextToUse =
+            
contextToUse.withValue(RequestDecompressionContext.COMPRESSED_SIZE_KEY, size)
+        }
+        otherCompressedSize.foreach { size =>
+          contextToUse =
+            
contextToUse.withValue(RequestDecompressionContext.OTHER_COMPRESSED_SIZE_KEY, 
size)
+        }
+
+        // Run the rest of the call chain with the context
+        val prev = contextToUse.attach()
+        try {
+          super.onMessage(decompressedReq.asInstanceOf[ReqT])
+        } finally {
+          contextToUse.detach(prev)
+        }
+      }
+    }
+  }
+
+  private def decompressExecutePlanRequest(request: proto.ExecutePlanRequest)
+      : (proto.ExecutePlanRequest, Option[Long], Option[Long]) = {
+    if (!request.hasPlan) {
+      return (request, None, None)
+    }
+    val (decompressedReq, size) = decompressPlanGeneric(
+      request,
+      request.getUserContext.getUserId,
+      request.getSessionId,
+      (r: proto.ExecutePlanRequest) => r.getPlan,
+      (req: proto.ExecutePlanRequest, plan: proto.Plan) => 
req.toBuilder.setPlan(plan).build())
+
+    (decompressedReq, size, None)
+  }
+
+  private def decompressAnalyzePlanRequest(request: proto.AnalyzePlanRequest)
+      : (proto.AnalyzePlanRequest, Option[Long], Option[Long]) = {
+    val userId = request.getUserContext.getUserId
+    val sessionId = request.getSessionId
+
+    // Helper to decompress a single-plan analysis type
+    def decompress(
+        req: proto.AnalyzePlanRequest,
+        getPlan: proto.AnalyzePlanRequest => proto.Plan,
+        rebuild: (proto.AnalyzePlanRequest, proto.Plan) => 
proto.AnalyzePlanRequest) = {
+      decompressPlanGeneric(req, userId, sessionId, getPlan, rebuild)
+    }
+
+    // NOTE: All AnalyzePlanRequest cases are explicitly listed here.
+    // The default case throws an exception to catch new cases at runtime and 
fail CI tests.
+    request.getAnalyzeCase match {
+      // Cases with Plan fields - decompress if compressed
+      case proto.AnalyzePlanRequest.AnalyzeCase.SCHEMA =>
+        val (req, size) = decompress(

Review Comment:
   I agree this refactoring will be better if many cases have many plans, but 
in fact, all the cases except the SameSemantics have only one plan. I think 
this approach will make it a bit harder to understand.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to