CRZbulabula commented on code in PR #18:
URL: https://github.com/apache/iotdb-mcp-server/pull/18#discussion_r3965101735


##########
src/iotdb_mcp_server/session_manager.py:
##########
@@ -0,0 +1,424 @@
+# 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
+
+from typing import Any, Callable, Mapping
+
+from iotdb.SessionPool import PoolConfig, SessionPool
+from iotdb.table_session import TableSession
+from iotdb.table_session_pool import TableSessionPoolConfig
+from iotdb.utils.exception import IoTDBConnectionException
+
+from iotdb_mcp_server.target_registry import (
+    IoTDBTarget,
+    IoTDBTargetRegistry,
+    merge_target,
+    target_from_mapping,
+)
+
+
+def target_from_config(config: Any) -> IoTDBTarget:
+    if isinstance(config, IoTDBTarget):
+        return config
+    if hasattr(config, "to_target"):
+        return config.to_target()
+
+    keys = (
+        "target_id",
+        "display_name",
+        "target_kind",
+        "kind",
+        "host",
+        "port",
+        "node_urls",
+        "user",
+        "password",
+        "database",
+        "sql_dialect",
+        "timezone",
+        "export_path",
+        "iotdb_home",
+        "use_ssl",
+        "ca_certs",
+        "connection_timeout_in_ms",
+        "enable_redirection",
+        "enable_compression",
+        "fetch_size",
+        "max_retry",
+        "max_pool_size",
+        "tree_wait_timeout_in_ms",
+        "table_wait_timeout_in_ms",
+        "policy",
+        "last_known_good_credential",
+        "verified_at",
+    )
+    payload: dict[str, Any] = {}
+    for key in keys:
+        if hasattr(config, key):
+            payload[key] = getattr(config, key)
+    if "target_kind" in payload and "kind" not in payload:
+        payload["kind"] = payload["target_kind"]
+    return target_from_mapping(payload)
+
+
+def _target_with_overrides(
+    config_or_target: Any,
+    overrides: Mapping[str, Any] | None = None,
+) -> IoTDBTarget:
+    target = target_from_config(config_or_target)
+    clean_overrides = {
+        key: value for key, value in (overrides or {}).items() if value is not 
None
+    }
+    if not clean_overrides:
+        return target
+    return merge_target(target, clean_overrides)
+
+
+def make_tree_pool_config(target: IoTDBTarget) -> PoolConfig:
+    return PoolConfig(
+        host=target.host,
+        port=target.port,
+        node_urls=None,
+        user_name=target.user,
+        password=target.password,
+        fetch_size=target.fetch_size,
+        time_zone=target.timezone,
+        max_retry=target.max_retry,
+        enable_compression=target.enable_compression,
+        enable_redirection=target.enable_redirection,
+        use_ssl=target.use_ssl,
+        ca_certs=target.ca_certs or None,
+        connection_timeout_in_ms=target.connection_timeout_in_ms,
+    )
+
+
+def make_table_pool_config(
+    target: IoTDBTarget, database: str | None = None
+) -> TableSessionPoolConfig:
+    resolved_database = database if database is not None else target.database
+    return TableSessionPoolConfig(
+        node_urls=list(target.node_urls),
+        username=target.user,
+        password=target.password,
+        max_pool_size=target.max_pool_size,
+        database=resolved_database or None,
+        fetch_size=target.fetch_size,
+        time_zone=target.timezone,
+        enable_redirection=target.enable_redirection,
+        enable_compression=target.enable_compression,
+        wait_timeout_in_ms=target.table_wait_timeout_in_ms,
+        max_retry=target.max_retry,
+        use_ssl=target.use_ssl,
+        ca_certs=target.ca_certs or None,
+        connection_timeout_in_ms=target.connection_timeout_in_ms,
+    )
+
+
+def create_tree_session_pool(
+    config_or_target: Any,
+    max_pool_size: int | None = None,
+    wait_timeout_in_ms: int | None = None,
+) -> SessionPool:
+    target = _target_with_overrides(
+        config_or_target,
+        {
+            "max_pool_size": max_pool_size,
+            "tree_wait_timeout_in_ms": wait_timeout_in_ms,
+        },
+    )
+    return SessionPool(
+        make_tree_pool_config(target),
+        target.max_pool_size,
+        target.tree_wait_timeout_in_ms,
+    )
+
+
+def create_table_session_pool(
+    config_or_target: Any,
+    max_pool_size: int | None = None,
+    database: str | None = None,
+    wait_timeout_in_ms: int | None = None,
+) -> Any:
+    target = _target_with_overrides(
+        config_or_target,
+        {
+            "max_pool_size": max_pool_size,
+            "database": database,
+            "table_wait_timeout_in_ms": wait_timeout_in_ms,
+        },
+    )
+    return _SingleEndpointTableSessionPool(target)
+
+
+class _SingleEndpointTableSessionPool:
+    """TableSessionPool equivalent that opens only the target's primary 
endpoint."""
+
+    def __init__(self, target: IoTDBTarget) -> None:
+        self.database = target.database or None
+        self._session_pool = SessionPool(
+            make_tree_pool_config(target),
+            target.max_pool_size,
+            target.table_wait_timeout_in_ms,
+        )
+        self._session_pool.sql_dialect = "table"
+        self._session_pool.database = self.database
+
+    def get_session(self) -> TableSession:
+        return TableSession(None, session_pool=self._session_pool)
+
+    def close(self) -> None:
+        self._session_pool.close()
+
+
+def is_iotdb_connection_error(error: BaseException) -> bool:
+    current: BaseException | None = error
+    seen: set[int] = set()
+    while current is not None and id(current) not in seen:
+        seen.add(id(current))
+        if isinstance(current, TimeoutError):
+            return False
+        if isinstance(current, (IoTDBConnectionException, ConnectionError, 
OSError)):
+            return True
+        message = str(current).lower()
+        if any(
+            marker in message
+            for marker in (
+                "801: authentication failed",
+                "status code 801",
+                "822:",
+                "status code 822",
+            )
+        ):
+            return True
+        current = current.__cause__ or current.__context__
+    return False
+
+
+class _ManagedSession:
+    def __init__(
+        self,
+        session: Any,
+        on_connection_error: Callable[[BaseException], None],
+        release_session: Callable[[Any], None] | None = None,
+    ):
+        self._session = session
+        self._on_connection_error = on_connection_error
+        self._release_session = release_session
+        self._broken = False
+        self._closed = False
+
+    def close(self) -> None:
+        if self._closed:
+            return
+        self._closed = True
+
+        if self._release_session is None:
+            self._session.close()

Review Comment:
   **[P1] Avoid returning broken TableSession objects to an already-closed 
pool**
   
   For table pools, `release_session` is `None` because `TableSession.close()` 
itself calls the underlying pool\x27s `put_back()`. When a table operation 
raises a connection error, `managed_call()` invokes `_on_connection_error`, 
which evicts the target and closes all pools before the service-level 
`finally`/`except` path calls `table_session.close()`. This then calls 
`put_back()` on the closed pool and raises a new `ConnectionError`, masking the 
original database failure. Please add a discard path for broken table sessions 
(or catch the closed-pool error here) so cleanup cannot replace the root 
cause.\n\nReproduction shape: mark a managed table session broken, close its 
pool from the connection-error callback, then call `table_session.close()`; the 
current implementation raises `ConnectionError: SessionPool has already been 
closed`.



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