dabla commented on code in PR #77716:
URL: https://github.com/apache/airflow/pull/77716#discussion_r4737372685


##########
providers/ftp/src/airflow/providers/ftp/fs/ftp.py:
##########
@@ -0,0 +1,120 @@
+# 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 ftplib
+from typing import TYPE_CHECKING, Any
+
+from fsspec.implementations.ftp import FTPFileSystem
+
+from airflow.providers.common.compat.sdk import BaseHook
+from airflow.providers.ftp.hooks.ftp import _get_passive_mode
+
+if TYPE_CHECKING:
+    from fsspec import AbstractFileSystem
+
+schemes = ["ftp"]
+
+
+class _AirflowFTPFileSystem(FTPFileSystem):
+    """
+    ``FTPFileSystem`` that honors the ``passive`` extra and recovers from a 
dropped control connection.
+
+    fsspec has no option for passive mode, so it is applied on every 
``_connect``. The filesystem
+    is cached for the life of the process, while fsspec reconnects only when 
aborting a cut-short
+    read fails, so calls on a connection the server has dropped fail or return 
wrong results. The
+    methods below therefore check the connection before they send a command 
and reconnect when it
+    is gone, including after a reconnect that failed and left an unconnected 
``ftplib.FTP`` behind.
+    Reads and writes on a file that is already open are not covered.
+    """
+
+    def __init__(self, *args: Any, passive: bool = True, **kwargs: Any) -> 
None:
+        self.passive = passive
+        super().__init__(*args, **kwargs)
+
+    def _connect(self) -> None:
+        super()._connect()
+        self.ftp.set_pasv(self.passive)
+
+    def _ensure_connected(self) -> None:
+        if self.ftp.sock is not None:
+            try:
+                self.ftp.voidcmd("NOOP")
+                return
+            except ftplib.all_errors:
+                pass
+        self._connect()
+
+    def ls(self, path, detail=True, **kwargs):
+        if self._strip_protocol(path) not in self.dircache:
+            self._ensure_connected()
+        return super().ls(path, detail=detail, **kwargs)
+
+    def _open(self, path, mode="rb", **kwargs):
+        self._ensure_connected()
+        return super()._open(path, mode=mode, **kwargs)
+
+    def get_file(self, rpath, lpath, **kwargs):
+        self._ensure_connected()
+        return super().get_file(rpath, lpath, **kwargs)
+
+    def cat_file(self, path, start=None, end=None, **kwargs):
+        self._ensure_connected()
+        return super().cat_file(path, start=start, end=end, **kwargs)
+
+    def _rm(self, path):
+        self._ensure_connected()
+        return super()._rm(path)
+
+    def mkdir(self, path, create_parents=True, **kwargs):
+        self._ensure_connected()
+        return super().mkdir(path, create_parents=create_parents, **kwargs)
+
+    def rmdir(self, path):
+        self._ensure_connected()
+        return super().rmdir(path)
+
+    def mv(self, path1, path2, **kwargs):
+        self._ensure_connected()
+        return super().mv(path1, path2, **kwargs)
+
+
+def get_fs(conn_id: str | None, storage_options: dict[str, Any] | None = None) 
-> AbstractFileSystem:
+    if conn_id is None:
+        manual_options = storage_options or {}
+        if not manual_options.get("host"):
+            raise ValueError("An FTP path needs a connection id, for example 
ftp://my_conn@/path/to/file.";)
+        return _AirflowFTPFileSystem(**manual_options)
+
+    conn = BaseHook.get_connection(conn_id)
+    extras = conn.extra_dejson
+
+    options: dict[str, Any] = {

Review Comment:
   **[warning]** A file that someone else creates after its folder was listed 
is never seen by this process. I missed this in the first round; it has the 
same cause as the idle-connection point.
   
   fsspec caches every directory listing in `dircache` with no expiry by 
default, `exists()`/`info()` answer from the parent's cached listing, and 
Airflow keeps the filesystem for the life of the process 
([`_STORE_CACHE`](https://github.com/apache/airflow/blob/f1aa05e7271b367243eba749762678ffdce57e0d/task-sdk/src/airflow/sdk/io/store.py#L127)).
 Only writes made through this filesystem invalidate the cache. On this head, 
against a local pyftpdlib server:
   
   ```
   fs.ls("/sub")                      -> ['a.csv']
   # another client creates /sub/late.csv
   fs.exists("/sub/late.csv")         -> False    # and stays False
   fs.ls("/sub", detail=False)        -> ['a.csv']
   ```
   
   So a task that waits for a file with `while not path.exists(): sleep(...)`, 
a sensor in poke mode, or anything in the triggerer never sees the file arrive. 
The cache is the `DirCache` that `AbstractFileSystem.__init__` builds from the 
storage options, so it can be bounded from `get_fs` without more code in the 
subclass. With the same steps:
   
   ```
   _AirflowFTPFileSystem(..., use_listings_cache=False)   -> exists() True
   _AirflowFTPFileSystem(..., listings_expiry_time=1)     -> exists() True 
after 1.2 s
   ```
   
   I would default to a short `listings_expiry_time` in `options` here (still 
overridable through `storage_options`) rather than switching the cache off: 
`ObjectStoragePath.copy` calls `is_dir()` per file of a folder, and without a 
cache each call is an `MLSD` of the parent. A line on the docs page about the 
default would help too.



##########
providers/ftp/src/airflow/providers/ftp/fs/ftp.py:
##########
@@ -0,0 +1,120 @@
+# 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 ftplib
+from typing import TYPE_CHECKING, Any
+
+from fsspec.implementations.ftp import FTPFileSystem
+
+from airflow.providers.common.compat.sdk import BaseHook
+from airflow.providers.ftp.hooks.ftp import _get_passive_mode
+
+if TYPE_CHECKING:
+    from fsspec import AbstractFileSystem
+
+schemes = ["ftp"]
+
+
+class _AirflowFTPFileSystem(FTPFileSystem):
+    """
+    ``FTPFileSystem`` that honors the ``passive`` extra and recovers from a 
dropped control connection.
+
+    fsspec has no option for passive mode, so it is applied on every 
``_connect``. The filesystem
+    is cached for the life of the process, while fsspec reconnects only when 
aborting a cut-short
+    read fails, so calls on a connection the server has dropped fail or return 
wrong results. The
+    methods below therefore check the connection before they send a command 
and reconnect when it
+    is gone, including after a reconnect that failed and left an unconnected 
``ftplib.FTP`` behind.
+    Reads and writes on a file that is already open are not covered.
+    """
+
+    def __init__(self, *args: Any, passive: bool = True, **kwargs: Any) -> 
None:
+        self.passive = passive
+        super().__init__(*args, **kwargs)
+
+    def _connect(self) -> None:
+        super()._connect()
+        self.ftp.set_pasv(self.passive)
+
+    def _ensure_connected(self) -> None:
+        if self.ftp.sock is not None:
+            try:
+                self.ftp.voidcmd("NOOP")
+                return
+            except ftplib.all_errors:
+                pass
+        self._connect()
+
+    def ls(self, path, detail=True, **kwargs):
+        if self._strip_protocol(path) not in self.dircache:
+            self._ensure_connected()
+        return super().ls(path, detail=detail, **kwargs)
+
+    def _open(self, path, mode="rb", **kwargs):
+        self._ensure_connected()
+        return super()._open(path, mode=mode, **kwargs)
+
+    def get_file(self, rpath, lpath, **kwargs):
+        self._ensure_connected()
+        return super().get_file(rpath, lpath, **kwargs)
+
+    def cat_file(self, path, start=None, end=None, **kwargs):
+        self._ensure_connected()
+        return super().cat_file(path, start=start, end=end, **kwargs)
+
+    def _rm(self, path):
+        self._ensure_connected()
+        return super()._rm(path)
+
+    def mkdir(self, path, create_parents=True, **kwargs):
+        self._ensure_connected()
+        return super().mkdir(path, create_parents=create_parents, **kwargs)
+
+    def rmdir(self, path):
+        self._ensure_connected()
+        return super().rmdir(path)
+
+    def mv(self, path1, path2, **kwargs):
+        self._ensure_connected()
+        return super().mv(path1, path2, **kwargs)
+
+
+def get_fs(conn_id: str | None, storage_options: dict[str, Any] | None = None) 
-> AbstractFileSystem:
+    if conn_id is None:
+        manual_options = storage_options or {}
+        if not manual_options.get("host"):
+            raise ValueError("An FTP path needs a connection id, for example 
ftp://my_conn@/path/to/file.";)
+        return _AirflowFTPFileSystem(**manual_options)

Review Comment:
   **[nit]** `passive` given as a string is only normalised on the connection 
branch.
   
   Here `get_fs(None, {"host": ..., "passive": "false"})` passes the string 
straight to the constructor, `set_pasv("false")` is truthy, and the server sees 
`PASV` (checked against a local pyftpdlib server). With a connection id the 
same value goes through `_get_passive_mode` and gives active mode. Normalising 
once in `_AirflowFTPFileSystem.__init__` would cover both branches and let the 
two lines at the end of `get_fs` go.



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