bolkedebruin commented on code in PR #37058:
URL: https://github.com/apache/airflow/pull/37058#discussion_r1468917908


##########
airflow/io/xcom.py:
##########
@@ -0,0 +1,111 @@
+# 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.
+from __future__ import annotations
+
+import json
+import sys
+import uuid
+from typing import TYPE_CHECKING, Any, TypeVar
+from urllib.parse import urlsplit
+
+from airflow.configuration import conf
+from airflow.io.path import ObjectStoragePath
+from airflow.models.xcom import BaseXCom
+from airflow.utils.json import XComDecoder, XComEncoder
+
+if TYPE_CHECKING:
+    from sqlalchemy.orm import Session
+
+    from airflow.models import XCom
+
+T = TypeVar("T")
+
+
+class XComObjectStoreBackend(BaseXCom):
+    """XCom backend that stores data in an object store."""
+
+    path = conf.get("core", "xcom_objectstore_path", fallback="")
+
+    @staticmethod
+    def _get_key(data: str) -> str:
+        path = conf.get("core", "xcom_objectstore_path", fallback="")
+        p = ObjectStoragePath(path)
+
+        url = urlsplit(data)
+        if url.scheme:
+            k = ObjectStoragePath(data)
+
+            if k.is_relative_to(p) is False:
+                raise ValueError(f"Invalid key: {data}")
+            else:
+                return data.replace(path, "", 1).lstrip("/")
+
+        raise ValueError(f"Not a valid url: {data}")
+
+    @staticmethod
+    def serialize_value(
+        value: T,
+        *,
+        key: str | None = None,
+        task_id: str | None = None,
+        dag_id: str | None = None,
+        run_id: str | None = None,
+        map_index: int | None = None,
+    ) -> bytes | str:
+        s_val = json.dumps(value, cls=XComEncoder).encode("utf-8")
+        path = conf.get("core", "xcom_objectstore_path", fallback="")
+        compression = conf.get("core", "xcom_objectstore_compression", 
fallback=None)
+        threshold = conf.getint("core", "xcom_objectstore_threshold", 
fallback=-1)
+
+        if path and -1 < threshold < sys.getsizeof(value):
+            p = ObjectStoragePath(path) / 
f"{run_id}/{task_id}/{str(uuid.uuid4())}"
+
+            if not p.exists():
+                p.parent.mkdir(parents=True, exist_ok=True)
+
+            with p.open("wb", compression=compression) as f:
+                f.write(s_val)
+
+            return BaseXCom.serialize_value(str(p))
+        else:
+            return s_val
+
+    @staticmethod
+    def deserialize_value(
+        result: XCom,
+    ) -> Any:
+        data = BaseXCom.deserialize_value(result)
+        path = conf.get("core", "xcom_objectstore_path", fallback="")
+        try:
+            p = ObjectStoragePath(path) / XComObjectStoreBackend._get_key(data)

Review Comment:
   I don't think the overhead is really there. Small values will not result in 
that extra call, because the key won't be valid and it will raise a ValueError 
and object storage won't be touched. 
   
   On your no 2 we store a reference to the path now in xcom if it has been 
written out to object storage. I think that works the same as you are 
suggesting and a schema change make it better.
   
   Basically what we do now is:
   
   Serialize value 
    if above > threshold then store in objectstorage and store path reference 
in db
    else store value in db
   
   The reference tells us whether it is in the db or on object storage. We do 
need to reach out to check.
   
   
   



-- 
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: commits-unsubscr...@airflow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to