diff libervia/backend/memory/disco.py @ 4306:94e0968987cd

plugin XEP-0033: code modernisation, improve delivery, data validation: - Code has been rewritten using Pydantic models and `async` coroutines for data validation and cleaner element parsing/generation. - Delivery has been completely rewritten. It now works even if server doesn't support multicast, and send to local multicast service first. Delivering to local multicast service first is due to bad support of XEP-0033 in server (notably Prosody which has an incomplete implementation), and the current impossibility to detect if a sub-domain service handles fully multicast or only for local domains. This is a workaround to have a good balance between backward compatilibity and use of bandwith, and to make it work with the incoming email gateway implementation (the gateway will only deliver to entities of its own domain). - disco feature checking now uses `async` corountines. `host` implementation still use Deferred return values for compatibility with legacy code. rel 450
author Goffi <goffi@goffi.org>
date Thu, 26 Sep 2024 16:12:01 +0200
parents 0d7bb4df2343
children 554a87ae17a6
line wrap: on
line diff
--- a/libervia/backend/memory/disco.py	Thu Sep 26 16:11:56 2024 +0200
+++ b/libervia/backend/memory/disco.py	Thu Sep 26 16:12:01 2024 +0200
@@ -1,8 +1,8 @@
 #!/usr/bin/env python3
 
 
-# SAT: a jabber client
-# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)
+# Libervia XMPP client
+# Copyright (C) 2009-2024 Jérôme Poisson (goffi@goffi.org)
 
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU Affero General Public License as published by
@@ -17,7 +17,9 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-from typing import Optional
+from typing import Iterable, Optional, cast
+
+from twisted.internet.interfaces import IReactorCore
 from libervia.backend.core.i18n import _
 from libervia.backend.core import exceptions
 from libervia.backend.core.log import getLogger
@@ -122,8 +124,13 @@
         self.hashes = HashManager(persistent.PersistentDict("disco"))
         return self.hashes.load()
 
-    @defer.inlineCallbacks
-    def hasFeature(self, client, feature, jid_=None, node=""):
+    async def has_feature(
+        self,
+        client: SatXMPPEntity,
+        feature: str,
+        jid_: jid.JID | None = None,
+        node: str = "",
+    ) -> bool:
         """Tell if an entity has the required feature
 
         @param feature: feature namespace
@@ -131,40 +138,52 @@
         @param node(unicode): optional node to use for disco request
         @return: a Deferred which fire a boolean (True if feature is available)
         """
-        disco_infos = yield self.get_infos(client, jid_, node)
-        defer.returnValue(feature in disco_infos.features)
+        disco_infos = await self.get_infos(client, jid_, node)
+        return feature in disco_infos.features
 
-    @defer.inlineCallbacks
-    def check_feature(self, client, feature, jid_=None, node=""):
-        """Like hasFeature, but raise an exception is feature is not Found
+    async def check_feature(
+        self,
+        client: SatXMPPEntity,
+        feature: str,
+        jid_: jid.JID | None = None,
+        node: str = "",
+    ) -> None:
+        """Like has_feature, but raise an exception is feature is not Found
 
         @param feature: feature namespace
         @param jid_: jid of the target, or None for profile's server
-        @param node(unicode): optional node to use for disco request
+        @param node: optional node to use for disco request
 
         @raise: exceptions.FeatureNotFound
         """
-        disco_infos = yield self.get_infos(client, jid_, node)
+        disco_infos = await self.get_infos(client, jid_, node)
         if not feature in disco_infos.features:
-            raise failure.Failure(exceptions.FeatureNotFound())
+            raise exceptions.FeatureNotFound()
 
-    @defer.inlineCallbacks
-    def check_features(self, client, features, jid_=None, identity=None, node=""):
+    async def check_features(
+        self,
+        client: SatXMPPEntity,
+        features: Iterable[str],
+        jid_: jid.JID | None = None,
+        identity: tuple[str, str] | None = None,
+        node: str = "",
+    ) -> None:
         """Like check_feature, but check several features at once, and check also identity
 
-        @param features(iterable[unicode]): features to check
-        @param jid_(jid.JID): jid of the target, or None for profile's server
-        @param node(unicode): optional node to use for disco request
-        @param identity(None, tuple(unicode, unicode): if not None, the entity must have an identity with this (category, type) tuple
+        @param features: features to check
+        @param jid_: jid of the target, or None for profile's server
+        @param node: optional node to use for disco request
+        @param identity: if not None, the entity must have an identity with this
+            (category, type) tuple
 
         @raise: exceptions.FeatureNotFound
         """
-        disco_infos = yield self.get_infos(client, jid_, node)
+        disco_infos = await self.get_infos(client, jid_, node)
         if not set(features).issubset(disco_infos.features):
-            raise failure.Failure(exceptions.FeatureNotFound())
+            raise exceptions.FeatureNotFound()
 
         if identity is not None and identity not in disco_infos.identities:
-            raise failure.Failure(exceptions.FeatureNotFound())
+            raise exceptions.FeatureNotFound()
 
     async def has_identity(
         self,
@@ -338,14 +357,19 @@
         )  # FIXME: one bad service make a general timeout
         return d
 
-    def find_features_set(self, client, features, identity=None, jid_=None):
+    async def find_features_set(
+        self,
+        client: SatXMPPEntity,
+        features: Iterable[str],
+        identity: tuple[str, str] | None = None,
+        jid_: jid.JID | None = None,
+    ) -> set[jid.JID]:
         """Return entities (including jid_ and its items) offering features
 
+        @param client: Client session.
         @param features: iterable of features which must be present
-        @param identity(None, tuple(unicode, unicode)): if not None, accept only this
-            (category/type) identity
+        @param identity: if not None, accept only this (category/type) identity
         @param jid_: the jid of the target server (None for profile's server)
-        @param profile: %(doc_profile)s
         @return: a set of found entities
         """
         if jid_ is None:
@@ -353,30 +377,24 @@
         features = set(features)
         found_entities = set()
 
-        def infos_cb(infos, entity):
+        def infos_cb(infos: disco.DiscoInfo, entity: jid.JID) -> None:
             if entity is None:
-                log.warning(_("received an item without jid"))
+                log.warning(_("Received an item without JID"))
                 return
             if identity is not None and identity not in infos.identities:
                 return
             if features.issubset(infos.features):
                 found_entities.add(entity)
 
-        def got_items(items):
-            defer_list = []
-            for entity in [jid_] + [item.entity for item in items]:
-                infos_d = self.get_infos(client, entity)
-                infos_d.addCallbacks(infos_cb, self._infos_eb, [entity], None, [entity])
-                defer_list.append(infos_d)
-            return defer.DeferredList(defer_list)
-
-        d = self.get_items(client, jid_)
-        d.addCallback(got_items)
-        d.addCallback(lambda __: found_entities)
-        reactor.callLater(
-            TIMEOUT, d.cancel
-        )  # FIXME: one bad service make a general timeout
-        return d
+        items = await self.get_items(client, jid_)
+        defer_list = []
+        for entity in [jid_] + [item.entity for item in items]:
+            infos_d = self.get_infos(client, entity)
+            infos_d.addCallbacks(infos_cb, self._infos_eb, [entity], None, [entity])
+            infos_d.addTimeout(TIMEOUT, cast(IReactorCore, reactor))
+            defer_list.append(infos_d)
+        await defer.DeferredList(defer_list)
+        return found_entities
 
     def generate_hash(self, services):
         """Generate a unique hash for given service