uranusjr commented on code in PR #77249:
URL: https://github.com/apache/airflow/pull/77249#discussion_r4688567597


##########
java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt:
##########
@@ -64,6 +76,34 @@ object Frame {
       REQUIRED_NULLABLE_REQUESTS.forEach { addMixIn(it, 
KeepNullFields::class.java) }
     }
 
+  /**
+   * Encodes values that task code hands to Airflow, using every Jackson module
+   * on the classpath and rejecting objects that have no properties to encode.
+   */
+  private val userValueMapper: ObjectMapper by lazy {
+    mapper.copy().apply {
+      registerModule(SimpleModule().setSerializerModifier(RejectEmptyBeans))
+      findAndRegisterModules()
+    }
+  }
+
+  /**
+   * Converts a user value into JSON-shaped data (maps, lists, strings, 
numbers,
+   * booleans, null) before it goes on the wire.
+   *
+   * @throws IllegalArgumentException if [value] is or contains an object with 
no
+   *   properties to encode, or a byte array.
+   */
+  internal fun encodeUserValue(value: Any?): Any? = encodeUserValue(value, 
userValueMapper)

Review Comment:
   Do we really need this? The function is only used in one place, and we can 
just pass in the mapper explicitly. Also does it need to be internal instead of 
private?



##########
java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt:
##########
@@ -64,6 +76,34 @@ object Frame {
       REQUIRED_NULLABLE_REQUESTS.forEach { addMixIn(it, 
KeepNullFields::class.java) }
     }
 
+  /**
+   * Encodes values that task code hands to Airflow, using every Jackson module
+   * on the classpath and rejecting objects that have no properties to encode.
+   */
+  private val userValueMapper: ObjectMapper by lazy {
+    mapper.copy().apply {
+      registerModule(SimpleModule().setSerializerModifier(RejectEmptyBeans))
+      findAndRegisterModules()

Review Comment:
   This fails atomically on any bad module. Use `findModules()` + per-module 
try instead.



##########
java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/TestValueModule.kt:
##########
@@ -0,0 +1,47 @@
+/*
+ * 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.airflow.sdk.execution
+
+import com.fasterxml.jackson.core.JsonGenerator
+import com.fasterxml.jackson.databind.SerializerProvider
+import com.fasterxml.jackson.databind.module.SimpleModule
+import com.fasterxml.jackson.databind.ser.std.StdSerializer
+
+/** A type with no properties, so it can only be encoded through 
[TestValueModule]. */
+class ModuleEncoded

Review Comment:
   We should write this in Java. Kotlin adds the `@Metadata` annotation to its 
classes, which suppresses `FAIL_ON_EMPTY_BEANS`, so the request mapper silently 
writes `{}`. Combined with the issue mentioned in the previous message, this 
hides the second-pass failure.



##########
airflow-core/docs/authoring-and-scheduling/language-sdks/java.rst:
##########
@@ -710,7 +710,9 @@ The ``Client``
        key, Dag, run, or one instance of a mapped task; a map index that 
selects no task instance reads
        ``null``. See the API reference. For the Java types values arrive as, 
see :ref:`java-sdk/types`.
    * - ``setXCom(value)`` / ``setXCom(key, value)``
-     - Publishes an XCom value. The value must be JSON-serializable.
+     - Publishes an XCom value. The value must be JSON-serializable. Objects 
are encoded with Jackson
+       and the Jackson modules in the bundle; an object with no properties to 
encode raises
+       ``IllegalArgumentException`` instead of being stored as ``{}``.

Review Comment:
   ```suggestion
        - Publishes an XCom value. The value must be JSON-serializable; see 
:ref:`java-sdk/types`.
   ```
   
   The rest of the description duplicates below. (I’m not sure if the reference 
is correct; check locally when you apply.)



##########
java-sdk/sdk/src/main/kotlin/org/apache/airflow/sdk/execution/Frame.kt:
##########
@@ -134,11 +174,49 @@ object Frame {
   }
 
   @Suppress("UNCHECKED_CAST")
-  private fun toBody(value: Any): Map<String, Any?> =
-    when (value) {
-      is Map<*, *> -> value as Map<String, Any?>
-      else -> mapper.convertValue(value, MutableMap::class.java) as 
MutableMap<String, Any?>
+  private fun toBody(value: Any): Map<String, Any?> {
+    if (value is Map<*, *>) return value as Map<String, Any?>
+    val userValue =
+      when (value) {
+        is SetXCom -> value.value
+        is SetTaskStateStore -> value.value
+        else -> return mapper.convertValue(value, MutableMap::class.java) as 
MutableMap<String, Any?>
+      }
+    val encoded = encodeUserValue(userValue)
+    return (mapper.convertValue(value, MutableMap::class.java) as 
MutableMap<String, Any?>).also {
+      if (encoded != null || "value" in it) it["value"] = encoded
     }

Review Comment:
   The raw value is still serialized by `mapper` inside `convertValue` and then 
overwritten, breaking module-serialized Java types without bean properties and 
repeats the work. Set the encoded value on the message before converting 
instead, so `mapper` never sees the raw object.



##########
java-sdk/sdk/src/test/kotlin/org/apache/airflow/sdk/execution/CommTest.kt:
##########
@@ -830,6 +830,149 @@ class CommsTest {
     comm.close()
   }
 
+  @Test
+  @DisplayName("setXCom rejects an object with no properties without writing 
anything to the supervisor")
+  @Timeout(value = 30, unit = TimeUnit.SECONDS)
+  fun setXComRejectsEmptyBeanBeforeWriting() {
+    val error = assertSetXComRejectedWithoutWriting(NoProperties())
+    Assertions.assertTrue(NoProperties::class.java.name in 
error.message.orEmpty(), error.message)
+    Assertions.assertTrue("would be stored as {}" in error.message.orEmpty(), 
error.message)
+  }
+
+  @Test
+  @DisplayName("setXCom rejects an object with no properties nested in a map 
or list")
+  @Timeout(value = 30, unit = TimeUnit.SECONDS)
+  fun setXComRejectsNestedEmptyBeanBeforeWriting() {
+    val inMap = assertSetXComRejectedWithoutWriting(mapOf("score" to 
NoProperties()))
+    Assertions.assertTrue(NoProperties::class.java.name in 
inMap.message.orEmpty(), inMap.message)
+    Assertions.assertTrue("[\"score\"]" in inMap.message.orEmpty(), "the error 
should name the path: ${inMap.message}")
+    val inList = assertSetXComRejectedWithoutWriting(listOf(1L, 
NoProperties()))
+    Assertions.assertTrue(NoProperties::class.java.name in 
inList.message.orEmpty(), inList.message)
+  }
+
+  @Test
+  @DisplayName("setXCom encodes a type with the Jackson module registered for 
it on the classpath")
+  @Timeout(value = 30, unit = TimeUnit.SECONDS)
+  fun setXComUsesJacksonModulesOnTheClasspath() {
+    val (body, failure) =
+      roundTrip(::emptyResponseFrame, setXComDetails()) {
+        it.setXCom(value = mapOf("custom" to listOf(ModuleEncoded())))
+      }
+    Assertions.assertNull(failure, "setXCom should return normally, got 
$failure")
+    Assertions.assertEquals(mapOf("custom" to listOf("encoded by 
TestValueModule")), body["value"])
+  }
+
+  @Test
+  @DisplayName("setXCom sends JSON scalars, maps and lists unchanged")
+  @Timeout(value = 30, unit = TimeUnit.SECONDS)
+  fun setXComSendsJsonValues() {
+    val details = setXComDetails()
+    for (value in listOf<Any>(42L, "ok", true, listOf(1L, 2L), mapOf("region" 
to "eu", "threshold" to 0.5))) {
+      val (body, failure) = roundTrip(::emptyResponseFrame, details) { 
it.setXCom(value = value) }
+      Assertions.assertNull(failure, "setXCom($value) should return normally, 
got $failure")
+      Assertions.assertEquals("SetXCom", body["type"])
+      Assertions.assertEquals(value, body["value"])
+    }
+  }
+
+  @Test
+  @DisplayName("setXCom still encodes a Java bean, enum and date-time as 
Jackson did before")

Review Comment:
   After this PR, "as Jackson did before" would no longer be meaningful. This 
should describe the behavior instead e.g. "encodes a Java bean as its 
properties".



-- 
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]

Reply via email to