From 8f8bb720f0229e8b2f218ed984722c9270e3aeb3 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 16:33:20 +0000 Subject: [PATCH] Key the cloud engines' cache on the request's evidence through the Cloud Request Engine A cloud engine accepts no evidence, so there is no key to use in a results cache of its own, as the Cloud Aspect Engine specification says under "Configuration options", where it recommends the cache goes on the Cloud Request Engine instead. - The cache setting of DeviceDetectionCloudPipelineBuilder, DeviceDetectionPipelineBuilder, IpIntelligenceCloudPipelineBuilder, IpIntelligencePipelineBuilder and LocationPipelineBuilder now adds the cache to the Cloud Request Engine, as .NET's cloud pipeline builders do. That engine keys the cache on the evidence it sends and applies its own cache rules, so a response made for one visitor is neither stored nor served, and a request that carries a session id, a sequence, JA4 or HTTP/2 settings, or a sealed result to redeem always goes to the cloud service. The on-premise branches are unchanged, because those engines already refuse a cache. - CloudEngine.set_cache raises an exception that names the Cloud Request Engine, as the on-premise engines refuse a cache, and CloudEngine.process never uses a cache of the engine's own. DerivedCloud inherits both, so a redeemed Human Confidence result is never stored or served again. - The builders' documentation says where the cache goes, and that with the JavaScript builder on every request carries a session id, which the Cloud Request Engine sends to the cloud service every time. A caller that put a cache on a cloud engine directly now gets the exception, and adds the cache to the Cloud Request Engine instead. Tests, each failing on rc and passing here: - test_builder_cache.py in fiftyone_devicedetection_cloud, fiftyone_ipintelligence_cloud and location, and in the two examples packages for the combined builders: the cache is on the Cloud Request Engine, two different requests give their own results, and the same evidence again is answered from the cache with the JavaScript builder off. - test_cloudengine_cache.py: a cloud engine refuses a cache and reads each response whatever it holds. - test_human_confidence.py: DerivedCloud refuses a cache, and one held anyway never serves a redeemed result. --- .../devicedetection_pipelinebuilder.py | 20 ++- .../devicedetection_cloud_pipelinebuilder.py | 16 ++- .../tests/test_builder_cache.py | 117 +++++++++++++++++ .../tests/test_builder_cache.py | 117 +++++++++++++++++ .../ipintelligence_pipelinebuilder.py | 20 ++- .../ipintelligence_cloud_pipelinebuilder.py | 14 +- .../tests/test_builder_cache.py | 123 ++++++++++++++++++ .../tests/test_builder_cache.py | 123 ++++++++++++++++++ .../location_pipelinebuilder.py | 14 +- location/tests/test_builder_cache.py | 121 +++++++++++++++++ .../cloudengine.py | 30 +++++ .../humanconfidence.py | 5 + .../tests/test_cloudengine_cache.py | 98 ++++++++++++++ .../tests/test_human_confidence.py | 27 +++- 14 files changed, 814 insertions(+), 31 deletions(-) create mode 100644 device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py create mode 100644 device-detection/fiftyone_devicedetection_examples/tests/test_builder_cache.py create mode 100644 ip-intelligence/fiftyone_ipintelligence_cloud/tests/test_builder_cache.py create mode 100644 ip-intelligence/fiftyone_ipintelligence_examples/tests/test_builder_cache.py create mode 100644 location/tests/test_builder_cache.py create mode 100644 pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py diff --git a/device-detection/fiftyone_devicedetection/src/fiftyone_devicedetection/devicedetection_pipelinebuilder.py b/device-detection/fiftyone_devicedetection/src/fiftyone_devicedetection/devicedetection_pipelinebuilder.py index e695c9c3..5527a47c 100644 --- a/device-detection/fiftyone_devicedetection/src/fiftyone_devicedetection/devicedetection_pipelinebuilder.py +++ b/device-detection/fiftyone_devicedetection/src/fiftyone_devicedetection/devicedetection_pipelinebuilder.py @@ -59,8 +59,13 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): * enable_cookies - whether cookies should be enabled * minify: Whether to minify the JavaScript @type cache: Cache - @param cache: An instance of the fiftyone.pipeline.engines.cache, for the cloud engine only. The on-premise engine raises an exception if one is supplied - class + @param cache: An instance of the fiftyone.pipeline.engines.cache + class, for the cloud only. It is added to the Cloud Request Engine, + which keys it on the evidence it sends and applies its own cache + rules. One of them sends a request that carries a session id to the + cloud service every time, and every request carries one while the + JavaScript builder is on. The on-premise engine raises an exception + if one is supplied. Cloud Engine Settings: @@ -150,6 +155,7 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): self._usage_sharing = None if "data_file_path" in settings: + # The engine raises an exception if a cache is supplied. del settings["settings"] device = DeviceDetectionOnPremise(**settings) @@ -157,12 +163,14 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): self._usage_sharing = ShareUsage() else : - self.add(CloudRequestEngine(settings)) + request_engine = CloudRequestEngine(settings) + + if "cache" in settings: + request_engine.set_cache(settings["cache"]) + + self.add(request_engine) device = DeviceDetectionCloud() - if "cache" in settings: - device.set_cache(settings["cache"]) - self.add(device) if self._usage_sharing is not None: diff --git a/device-detection/fiftyone_devicedetection_cloud/src/fiftyone_devicedetection_cloud/devicedetection_cloud_pipelinebuilder.py b/device-detection/fiftyone_devicedetection_cloud/src/fiftyone_devicedetection_cloud/devicedetection_cloud_pipelinebuilder.py index a50325e7..a20a28ee 100644 --- a/device-detection/fiftyone_devicedetection_cloud/src/fiftyone_devicedetection_cloud/devicedetection_cloud_pipelinebuilder.py +++ b/device-detection/fiftyone_devicedetection_cloud/src/fiftyone_devicedetection_cloud/devicedetection_cloud_pipelinebuilder.py @@ -58,7 +58,11 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): * minify: Whether to minify the JavaScript @type cache: Cache @param cache: An instance of the fiftyone.pipeline.engines.cache - class + class. It is added to the Cloud Request Engine, which keys it on + the evidence it sends and applies its own cache rules. One of them + sends a request that carries a session id to the cloud service + every time, and every request carries one while the JavaScript + builder is on. Cloud Engine Settings: @@ -81,11 +85,11 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): # Add specific engines - self.add(CloudRequestEngine(settings)) - device = DeviceDetectionCloud() + request_engine = CloudRequestEngine(settings) if "cache" in settings: - device.set_cache(settings["cache"]) - - self.add(device) + request_engine.set_cache(settings["cache"]) + + self.add(request_engine) + self.add(DeviceDetectionCloud()) diff --git a/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py b/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py new file mode 100644 index 00000000..7630558a --- /dev/null +++ b/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py @@ -0,0 +1,117 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""! +The Device Detection Cloud Pipeline Builder adds its cache setting to the +Cloud Request Engine, which keys it on the evidence it sends. These tests +need no network connection and no resource key. +""" + +import json +import unittest +from unittest.mock import Mock + +from requests import Response + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache + +from fiftyone_devicedetection_cloud.devicedetection_cloud_pipelinebuilder import DeviceDetectionCloudPipelineBuilder + +IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X)" +ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8)" + + +class StandInCloud(RequestClient): + """! + Stands in for the cloud service, answering each request for data with + the User-Agent it was sent as the browser name, and counting them. + """ + + def __init__(self): + self.data_requests = 0 + + def request(self, type, url, content, originHeader, timeout_seconds=None): + if "accessibleProperties" in url: + body = {"Products": {"device": { + "DataTier": "CloudV4Free", + "Properties": [{"Name": "BrowserName", "Type": "String", + "Category": "Browser"}]}}} + elif "evidencekeys" in url: + body = ["header.user-agent", "query.user-agent"] + else: + self.data_requests += 1 + body = {"device": { + "browsername": dict(content or {}).get("user-agent")}} + response = Mock(spec=Response) + response.status_code = 200 + response.text = json.dumps(body) + response.content = response.text.encode("utf-8") + response.json = lambda: json.loads(response.text) + return response + + +class BuilderCacheTests(unittest.TestCase): + + def pipeline(self, cloud, cache, **settings): + pipeline = DeviceDetectionCloudPipelineBuilder( + resource_key="a-resource-key", http_client=cloud, cache=cache, + **settings).build() + self.addCleanup(pipeline.close) + return pipeline + + @staticmethod + def browser_name(pipeline, user_agent): + data = pipeline.create_flowdata() + data.evidence.add("header.user-agent", user_agent) + data.process() + return data.device.browsername.value() + + def test_the_cache_is_added_to_the_cloud_request_engine(self): + cache = LRUEngineCache() + pipeline = self.pipeline(StandInCloud(), cache) + + self.assertIs(cache, pipeline.get_element("cloud").cache) + self.assertFalse(hasattr(pipeline.get_element("device"), "cache")) + + def test_two_user_agents_give_two_results(self): + pipeline = self.pipeline(StandInCloud(), LRUEngineCache()) + + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(ANDROID, self.browser_name(pipeline, ANDROID)) + + def test_the_same_user_agent_again_is_answered_from_the_cache(self): + # With the JavaScript builder, the sequence element gives every + # request a session id, which the Cloud Request Engine never + # answers from its cache, so the JavaScript builder is off here. + cloud = StandInCloud() + pipeline = self.pipeline( + cloud, LRUEngineCache(), add_javascript_builder=False) + + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(ANDROID, self.browser_name(pipeline, ANDROID)) + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(2, cloud.data_requests) + + +if __name__ == "__main__": + unittest.main() diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_builder_cache.py b/device-detection/fiftyone_devicedetection_examples/tests/test_builder_cache.py new file mode 100644 index 00000000..48fee47f --- /dev/null +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_builder_cache.py @@ -0,0 +1,117 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The Device Detection builder, given a resource key, adds its cache setting +to the Cloud Request Engine, which keys it on the evidence it sends. The +fiftyone_devicedetection package has no tests of its own, so its builder is +tested here. These tests need no network connection and no resource key. +""" + +import json +import unittest +from unittest.mock import Mock + +from requests import Response + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache +from fiftyone_devicedetection.devicedetection_pipelinebuilder import DeviceDetectionPipelineBuilder + +IPHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X)" +ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8)" + + +class StandInCloud(RequestClient): + """ + Stands in for the cloud service, answering each request for data with + the User-Agent it was sent as the browser name, and counting them. + """ + + def __init__(self): + self.data_requests = 0 + + def request(self, type, url, content, originHeader, timeout_seconds=None): + if "accessibleProperties" in url: + body = {"Products": {"device": { + "DataTier": "CloudV4Free", + "Properties": [{"Name": "BrowserName", "Type": "String", + "Category": "Browser"}]}}} + elif "evidencekeys" in url: + body = ["header.user-agent", "query.user-agent"] + else: + self.data_requests += 1 + body = {"device": { + "browsername": dict(content or {}).get("user-agent")}} + response = Mock(spec=Response) + response.status_code = 200 + response.text = json.dumps(body) + response.content = response.text.encode("utf-8") + response.json = lambda: json.loads(response.text) + return response + + +class BuilderCacheTests(unittest.TestCase): + + def pipeline(self, cloud, cache, **settings): + pipeline = DeviceDetectionPipelineBuilder( + resource_key="a-resource-key", http_client=cloud, cache=cache, + **settings).build() + self.addCleanup(pipeline.close) + return pipeline + + @staticmethod + def browser_name(pipeline, user_agent): + data = pipeline.create_flowdata() + data.evidence.add("header.user-agent", user_agent) + data.process() + return data.device.browsername.value() + + def test_the_cache_is_added_to_the_cloud_request_engine(self): + cache = LRUEngineCache() + pipeline = self.pipeline(StandInCloud(), cache) + + self.assertIs(cache, pipeline.get_element("cloud").cache) + self.assertFalse(hasattr(pipeline.get_element("device"), "cache")) + + def test_two_user_agents_give_two_results(self): + pipeline = self.pipeline(StandInCloud(), LRUEngineCache()) + + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(ANDROID, self.browser_name(pipeline, ANDROID)) + + def test_the_same_user_agent_again_is_answered_from_the_cache(self): + # With the JavaScript builder, the sequence element gives every + # request a session id, which the Cloud Request Engine never + # answers from its cache, so the JavaScript builder is off here. + cloud = StandInCloud() + pipeline = self.pipeline( + cloud, LRUEngineCache(), add_javascript_builder=False) + + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(ANDROID, self.browser_name(pipeline, ANDROID)) + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(2, cloud.data_requests) + + +if __name__ == "__main__": + unittest.main() diff --git a/ip-intelligence/fiftyone_ipintelligence/src/fiftyone_ipintelligence/ipintelligence_pipelinebuilder.py b/ip-intelligence/fiftyone_ipintelligence/src/fiftyone_ipintelligence/ipintelligence_pipelinebuilder.py index a3eb676f..b4adb3da 100644 --- a/ip-intelligence/fiftyone_ipintelligence/src/fiftyone_ipintelligence/ipintelligence_pipelinebuilder.py +++ b/ip-intelligence/fiftyone_ipintelligence/src/fiftyone_ipintelligence/ipintelligence_pipelinebuilder.py @@ -57,8 +57,13 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): * enable_cookies - whether cookies should be enabled * minify: Whether to minify the JavaScript @type cache: Cache - @param cache: An instance of the fiftyone.pipeline.engines.cache, for the cloud engine only. The on-premise engine raises an exception if one is supplied - class + @param cache: An instance of the fiftyone.pipeline.engines.cache + class, for the cloud only. It is added to the Cloud Request Engine, + which keys it on the evidence it sends and applies its own cache + rules. One of them sends a request that carries a session id to the + cloud service every time, and every request carries one while the + JavaScript builder is on. The on-premise engine raises an exception + if one is supplied. Cloud Engine Settings: @@ -127,6 +132,7 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): self._usage_sharing = None if "data_file_path" in settings: + # The engine raises an exception if a cache is supplied. del settings["settings"] ip_engine = IpIntelligenceOnPremise(**settings) @@ -134,11 +140,13 @@ def __init__(self, settings = None, usage_sharing = True, **kwargs): self._usage_sharing = ShareUsage() else : - self.add(CloudRequestEngine(settings)) - ip_engine = IpIntelligenceCloud() + request_engine = CloudRequestEngine(settings) + + if "cache" in settings: + request_engine.set_cache(settings["cache"]) - if "cache" in settings: - ip_engine.set_cache(settings["cache"]) + self.add(request_engine) + ip_engine = IpIntelligenceCloud() self.add(ip_engine) diff --git a/ip-intelligence/fiftyone_ipintelligence_cloud/src/fiftyone_ipintelligence_cloud/ipintelligence_cloud_pipelinebuilder.py b/ip-intelligence/fiftyone_ipintelligence_cloud/src/fiftyone_ipintelligence_cloud/ipintelligence_cloud_pipelinebuilder.py index 45912864..b4d3273e 100644 --- a/ip-intelligence/fiftyone_ipintelligence_cloud/src/fiftyone_ipintelligence_cloud/ipintelligence_cloud_pipelinebuilder.py +++ b/ip-intelligence/fiftyone_ipintelligence_cloud/src/fiftyone_ipintelligence_cloud/ipintelligence_cloud_pipelinebuilder.py @@ -53,7 +53,11 @@ def __init__(self, settings = None, **kwargs): * minify: Whether to minify the JavaScript @type cache: Cache @param cache: An instance of the fiftyone.pipeline.engines.cache - class + class. It is added to the Cloud Request Engine, which keys it on + the evidence it sends and applies its own cache rules. One of them + sends a request that carries a session id to the cloud service + every time, and every request carries one while the JavaScript + builder is on. Cloud Engine Settings: @@ -78,10 +82,10 @@ def __init__(self, settings = None, **kwargs): # Add specific engines - self.add(CloudRequestEngine(settings)) - ip_engine = IpIntelligenceCloud() + request_engine = CloudRequestEngine(settings) if "cache" in settings: - ip_engine.set_cache(settings["cache"]) + request_engine.set_cache(settings["cache"]) - self.add(ip_engine) + self.add(request_engine) + self.add(IpIntelligenceCloud()) diff --git a/ip-intelligence/fiftyone_ipintelligence_cloud/tests/test_builder_cache.py b/ip-intelligence/fiftyone_ipintelligence_cloud/tests/test_builder_cache.py new file mode 100644 index 00000000..5b094703 --- /dev/null +++ b/ip-intelligence/fiftyone_ipintelligence_cloud/tests/test_builder_cache.py @@ -0,0 +1,123 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""! +The IP Intelligence Cloud Pipeline Builder adds its cache setting to the +Cloud Request Engine, which keys it on the evidence it sends. These tests +need no network connection and no resource key. +""" + +import json +import unittest +from unittest.mock import Mock + +from requests import Response + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache + +from fiftyone_ipintelligence_cloud.ipintelligence_cloud_pipelinebuilder import IpIntelligenceCloudPipelineBuilder + +IP_EVIDENCE = "query.client-ip-51d" +FIRST_ADDRESS = "185.28.167.78" +SECOND_ADDRESS = "2001:4860:4860::8888" + + +class StandInCloud(RequestClient): + """! + Stands in for the cloud service, answering each request for data with + the IP address it was sent as the registered name, and counting them. + """ + + def __init__(self): + self.data_requests = 0 + + def request(self, type, url, content, originHeader, timeout_seconds=None): + if "accessibleProperties" in url: + body = {"Products": {"ip": { + "DataTier": "CloudV4Free", + "Properties": [{"Name": "RegisteredName", "Type": "String", + "Category": "IP Metrics"}]}}} + elif "evidencekeys" in url: + body = [IP_EVIDENCE, "server.client-ip-51d"] + else: + self.data_requests += 1 + body = {"ip": { + "registeredname": dict(content or {}).get("client-ip-51d")}} + response = Mock(spec=Response) + response.status_code = 200 + response.text = json.dumps(body) + response.content = response.text.encode("utf-8") + response.json = lambda: json.loads(response.text) + return response + + +class BuilderCacheTests(unittest.TestCase): + + def pipeline(self, cloud, cache, **settings): + pipeline = IpIntelligenceCloudPipelineBuilder( + resource_key="a-resource-key", http_client=cloud, cache=cache, + **settings).build() + self.addCleanup(pipeline.close) + return pipeline + + @staticmethod + def registered_name(pipeline, address): + data = pipeline.create_flowdata() + data.evidence.add(IP_EVIDENCE, address) + data.process() + return data.ip.registeredname.value() + + def test_the_cache_is_added_to_the_cloud_request_engine(self): + cache = LRUEngineCache() + pipeline = self.pipeline(StandInCloud(), cache) + + self.assertIs(cache, pipeline.get_element("cloud").cache) + self.assertFalse(hasattr(pipeline.get_element("ip"), "cache")) + + def test_two_addresses_give_two_results(self): + pipeline = self.pipeline(StandInCloud(), LRUEngineCache()) + + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual( + SECOND_ADDRESS, self.registered_name(pipeline, SECOND_ADDRESS)) + + def test_the_same_address_again_is_answered_from_the_cache(self): + # With the JavaScript builder, the sequence element gives every + # request a session id, which the Cloud Request Engine never + # answers from its cache, so the JavaScript builder is off here. + cloud = StandInCloud() + pipeline = self.pipeline( + cloud, LRUEngineCache(), add_javascript_builder=False) + + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual( + SECOND_ADDRESS, self.registered_name(pipeline, SECOND_ADDRESS)) + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual(2, cloud.data_requests) + + +if __name__ == "__main__": + unittest.main() diff --git a/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_builder_cache.py b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_builder_cache.py new file mode 100644 index 00000000..dff3659f --- /dev/null +++ b/ip-intelligence/fiftyone_ipintelligence_examples/tests/test_builder_cache.py @@ -0,0 +1,123 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The IP Intelligence builder, given a resource key, adds its cache setting +to the Cloud Request Engine, which keys it on the evidence it sends. The +fiftyone_ipintelligence package has no tests of its own, so its builder is +tested here. These tests need no network connection and no resource key. +""" + +import json +import unittest +from unittest.mock import Mock + +from requests import Response + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache +from fiftyone_ipintelligence.ipintelligence_pipelinebuilder import IpIntelligencePipelineBuilder + +IP_EVIDENCE = "query.client-ip-51d" +FIRST_ADDRESS = "185.28.167.78" +SECOND_ADDRESS = "2001:4860:4860::8888" + + +class StandInCloud(RequestClient): + """ + Stands in for the cloud service, answering each request for data with + the IP address it was sent as the registered name, and counting them. + """ + + def __init__(self): + self.data_requests = 0 + + def request(self, type, url, content, originHeader, timeout_seconds=None): + if "accessibleProperties" in url: + body = {"Products": {"ip": { + "DataTier": "CloudV4Free", + "Properties": [{"Name": "RegisteredName", "Type": "String", + "Category": "IP Metrics"}]}}} + elif "evidencekeys" in url: + body = [IP_EVIDENCE, "server.client-ip-51d"] + else: + self.data_requests += 1 + body = {"ip": { + "registeredname": dict(content or {}).get("client-ip-51d")}} + response = Mock(spec=Response) + response.status_code = 200 + response.text = json.dumps(body) + response.content = response.text.encode("utf-8") + response.json = lambda: json.loads(response.text) + return response + + +class BuilderCacheTests(unittest.TestCase): + + def pipeline(self, cloud, cache, **settings): + pipeline = IpIntelligencePipelineBuilder( + resource_key="a-resource-key", http_client=cloud, cache=cache, + **settings).build() + self.addCleanup(pipeline.close) + return pipeline + + @staticmethod + def registered_name(pipeline, address): + data = pipeline.create_flowdata() + data.evidence.add(IP_EVIDENCE, address) + data.process() + return data.ip.registeredname.value() + + def test_the_cache_is_added_to_the_cloud_request_engine(self): + cache = LRUEngineCache() + pipeline = self.pipeline(StandInCloud(), cache) + + self.assertIs(cache, pipeline.get_element("cloud").cache) + self.assertFalse(hasattr(pipeline.get_element("ip"), "cache")) + + def test_two_addresses_give_two_results(self): + pipeline = self.pipeline(StandInCloud(), LRUEngineCache()) + + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual( + SECOND_ADDRESS, self.registered_name(pipeline, SECOND_ADDRESS)) + + def test_the_same_address_again_is_answered_from_the_cache(self): + # With the JavaScript builder, the sequence element gives every + # request a session id, which the Cloud Request Engine never + # answers from its cache, so the JavaScript builder is off here. + cloud = StandInCloud() + pipeline = self.pipeline( + cloud, LRUEngineCache(), add_javascript_builder=False) + + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual( + SECOND_ADDRESS, self.registered_name(pipeline, SECOND_ADDRESS)) + self.assertEqual( + FIRST_ADDRESS, self.registered_name(pipeline, FIRST_ADDRESS)) + self.assertEqual(2, cloud.data_requests) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/src/fiftyone_location/location_pipelinebuilder.py b/location/src/fiftyone_location/location_pipelinebuilder.py index a4599a52..a1b99040 100644 --- a/location/src/fiftyone_location/location_pipelinebuilder.py +++ b/location/src/fiftyone_location/location_pipelinebuilder.py @@ -41,7 +41,10 @@ class LocationPipelineBuilder(PipelineBuilder): @param settings: Settings for the pipeline. Can contain a `cloud_endpoint` url if overriding the default one. An optional cache can be added by passing an instance of - the DataKeyedCache class as a `cache` setting + the DataKeyedCache class as a `cache` setting. It is added to the Cloud Request Engine, + which keys it on the evidence it sends and applies its own cache rules. One of them + sends a request that carries a session id to the cloud service every time, and every + request carries one while the JavaScript builder is on. The pipeline builder can also contain javascript_builder_settings settings see the documentation for the base PipelineBuilder and JavaScriptBuilder class @@ -54,12 +57,11 @@ def __init__(self, resource_key, location_provider="fiftyonedegrees", settings={ settings["resource_key"] = resource_key - self.add(CloudRequestEngine(settings)) - - location = LocationCloud(location_provider=location_provider) + request_engine = CloudRequestEngine(settings) if "cache" in settings: - location.set_cache(settings["cache"]) + request_engine.set_cache(settings["cache"]) - self.add(location) + self.add(request_engine) + self.add(LocationCloud(location_provider=location_provider)) diff --git a/location/tests/test_builder_cache.py b/location/tests/test_builder_cache.py new file mode 100644 index 00000000..7f8c9feb --- /dev/null +++ b/location/tests/test_builder_cache.py @@ -0,0 +1,121 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""! +The Location Pipeline Builder adds its cache setting to the Cloud Request +Engine, which keys it on the evidence it sends. These tests need no network +connection and no resource key. +""" + +import json +import unittest +from unittest.mock import Mock + +from requests import Response + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache + +from fiftyone_location.location_pipelinebuilder import LocationPipelineBuilder + +LATITUDE = "query.51D_Pos_latitude" +LONGITUDE = "query.51D_Pos_longitude" +READING = ("51.4584", "-0.9706") +OXFORD = ("51.7520", "-1.2577") + + +class StandInCloud(RequestClient): + """! + Stands in for the cloud service, answering each request for data with + the position it was sent as the town, and counting them. + """ + + def __init__(self): + self.data_requests = 0 + + def request(self, type, url, content, originHeader, timeout_seconds=None): + if "accessibleProperties" in url: + body = {"Products": {"location": { + "DataTier": "CloudV4Free", + "Properties": [{"Name": "Town", "Type": "String", + "Category": "Location"}]}}} + elif "evidencekeys" in url: + body = [LATITUDE, LONGITUDE] + else: + self.data_requests += 1 + content = dict(content or {}) + body = {"location": {"town": content.get("51D_Pos_latitude") + + "," + content.get("51D_Pos_longitude")}} + response = Mock(spec=Response) + response.status_code = 200 + response.text = json.dumps(body) + response.content = response.text.encode("utf-8") + response.json = lambda: json.loads(response.text) + return response + + +class BuilderCacheTests(unittest.TestCase): + + def pipeline(self, cloud, cache, **settings): + settings.update({"http_client": cloud, "cache": cache}) + pipeline = LocationPipelineBuilder( + resource_key="a-resource-key", settings=settings).build() + self.addCleanup(pipeline.close) + return pipeline + + @staticmethod + def town(pipeline, position): + data = pipeline.create_flowdata() + data.evidence.add(LATITUDE, position[0]) + data.evidence.add(LONGITUDE, position[1]) + data.process() + return data.location.town.value() + + def test_the_cache_is_added_to_the_cloud_request_engine(self): + cache = LRUEngineCache() + pipeline = self.pipeline(StandInCloud(), cache) + + self.assertIs(cache, pipeline.get_element("cloud").cache) + self.assertFalse(hasattr(pipeline.get_element("location"), "cache")) + + def test_two_positions_give_two_results(self): + pipeline = self.pipeline(StandInCloud(), LRUEngineCache()) + + self.assertEqual(",".join(READING), self.town(pipeline, READING)) + self.assertEqual(",".join(OXFORD), self.town(pipeline, OXFORD)) + + def test_the_same_position_again_is_answered_from_the_cache(self): + # With the JavaScript builder, the sequence element gives every + # request a session id, which the Cloud Request Engine never + # answers from its cache, so the JavaScript builder is off here. + cloud = StandInCloud() + pipeline = self.pipeline( + cloud, LRUEngineCache(), add_javascript_builder=False) + + self.assertEqual(",".join(READING), self.town(pipeline, READING)) + self.assertEqual(",".join(OXFORD), self.town(pipeline, OXFORD)) + self.assertEqual(",".join(READING), self.town(pipeline, READING)) + self.assertEqual(2, cloud.data_requests) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py index cc6e910e..258b30bd 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py @@ -46,6 +46,12 @@ # The values HumanConfidence can have. Unknown is not one of them. HUMAN_CONFIDENCE_VALUES = ("High", "Medium", "Low") +# Why a cache on a cloud engine is refused. +CACHE_ON_REQUEST_ENGINE = ( + "A cloud engine accepts no evidence, so there is no key to use in a " + "results cache. Add the cache to the Cloud Request Engine instead, as " + "the pipeline builders' cache setting does.") + class OnPremiseMissingPropertyService(MissingPropertyService): def check(self, key, flow_element): @@ -86,6 +92,30 @@ def get_evidence_key_filter(self): return BasicListEvidenceKeyFilter([]) + def set_cache(self, cache): + + """! + Not supported. A cloud engine accepts no evidence, so there is no + key to use in a cache, as the Cloud Aspect Engine specification + says. The Cloud Request Engine's cache is keyed on the evidence it + sends and holds the response this engine reads, so the cache goes + there. + """ + + raise Exception(CACHE_ON_REQUEST_ENGINE) + + def process(self, flowdata): + + """! + Process the response with no cache of this engine's own, whatever + the engine holds, as set_cache says. + + @type flowdata: FlowData + @param flowdata: FlowData to process + """ + + return self.process_internal(flowdata) + def on_registration(self, pipeline): """! diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py index dffd08e2..bef83757 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -338,6 +338,11 @@ class DerivedCloud(CloudEngine): this engine gives only those two properties: Medium and no source on a request that carries a sealed result, and no value, with the reason, on any other request. + + Like every cloud engine, it refuses a cache and never uses one, so a + redeemed result is never stored or served again. The Cloud Request + Engine's cache neither stores nor serves a response to a request that + carries a sealed result. """ DATA_KEY = "derived" diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py new file mode 100644 index 00000000..3c2f24b9 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py @@ -0,0 +1,98 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +A cloud engine accepts no evidence, so there is no key to use in a cache of +its own. It refuses one, and reads the response of each request whatever it +holds. The cache goes on the Cloud Request Engine instead. +""" + +import json +import unittest + +from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine +from fiftyone_pipeline_core.basiclist_evidence_keyfilter import \ + BasicListEvidenceKeyFilter +from fiftyone_pipeline_core.elementdata_dictionary import ElementDataDictionary +from fiftyone_pipeline_core.flowelement import FlowElement +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder +from fiftyone_pipeline_engines.basic_dictionary_cache import \ + BasicDictionaryCache + +USER_AGENT = "header.user-agent" + + +class StandInRequestEngine(FlowElement): + """Stands in for a Cloud Request Engine, answering each request with the + User-Agent it carries as the value of the device section.""" + + def __init__(self): + super(StandInRequestEngine, self).__init__() + self.datakey = "cloud" + self.flow_element_properties = { + "device": {"value": {"name": "value", "type": "String"}}} + + def get_evidence_key_filter(self): + return BasicListEvidenceKeyFilter([USER_AGENT]) + + def process_internal(self, flowdata): + answer = {"device": {"value": flowdata.evidence.get(USER_AGENT)}} + flowdata.set_element_data(ElementDataDictionary( + self, {"cloud": json.dumps(answer)})) + + +class CloudEngineCacheTests(unittest.TestCase): + + @staticmethod + def device_engine(): + engine = CloudEngine() + engine.datakey = "device" + return engine + + def test_a_cloud_engine_refuses_a_cache(self): + with self.assertRaises(Exception) as context: + self.device_engine().set_cache(BasicDictionaryCache()) + self.assertIn("Cloud Request Engine", str(context.exception)) + + def test_a_cloud_engine_reads_each_response_whatever_it_holds(self): + engine = self.device_engine() + # set_cache refuses a cache, so the engine is given one directly. + engine.cache = BasicDictionaryCache() + pipeline = PipelineBuilder({ + "add_javascript_builder": False, + "use_setheader_properties": False}) \ + .add(StandInRequestEngine()).add(engine).build() + self.addCleanup(pipeline.close) + + values = [] + for user_agent in ("first", "second"): + data = pipeline.create_flowdata() + data.evidence.add(USER_AGENT, user_agent) + data.process() + values.append(data.device.value.value()) + + self.assertEqual(["first", "second"], values) + self.assertEqual({}, engine.cache.cache) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py index 88e07008..9c3d412b 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py @@ -122,7 +122,8 @@ def setUp(self): self.cloud = StandIn() self.transactions = HumanConfidenceTransactions() - def pipeline(self, license_key=LICENCE, cache=None, requested=None): + def pipeline(self, license_key=LICENCE, cache=None, requested=None, + derived=None): settings = { "resource_key": RESOURCE, "http_client": self.cloud, "cloud_endpoint": API, @@ -138,7 +139,7 @@ def pipeline(self, license_key=LICENCE, cache=None, requested=None): "add_javascript_builder": False, "use_setheader_properties": False, "suppress_process_exceptions": True}) \ - .add(engine).add(DerivedCloud()).build() + .add(engine).add(derived or DerivedCloud()).build() self.addCleanup(pipeline.close) return pipeline @@ -421,6 +422,28 @@ def test_two_reads_make_one_request(self): self.assertEqual(first, second) self.assertEqual(1, len(self.cloud.data_requests)) + def test_derived_cloud_refuses_a_cache(self): + with self.assertRaises(Exception) as context: + DerivedCloud().set_cache(BasicDictionaryCache()) + self.assertIn("Cloud Request Engine", str(context.exception)) + + def test_a_cache_on_derived_cloud_never_serves_a_redeemed_result(self): + derived = DerivedCloud() + # set_cache refuses a cache, so the engine is given one directly. + derived.cache = BasicDictionaryCache() + pipeline = self.pipeline(derived=derived) + self.cloud.answer = reply({"derived": { + "humanconfidence": "High", "humanconfidencesource": "Active"}}) + self.assert_values(self.process(pipeline), "High", "Active") + + self.cloud.answer = reply({"derived": { + "humanconfidence": "Low", "humanconfidencesource": "Passive"}}) + self.assert_values( + self.process(pipeline, sealed=None, page=None), "Low", "Passive") + self.assert_values(self.process(pipeline), "Low", "Passive") + self.assertEqual(3, len(self.cloud.data_requests)) + self.assertEqual({}, derived.cache.cache) + def test_a_request_with_a_sealed_result_skips_the_cache(self): cache = BasicDictionaryCache() pipeline = self.pipeline(cache=cache)