From 8f18579fb9bcd3bbc246e496d358db6593d91e5b Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:05:18 +0000 Subject: [PATCH 1/7] TEST: Prove each value made for one visitor keeps a request out of the cache The Cloud Request Engine sends a request carrying a session id, a sequence, a JA4 or HTTP/2 settings to the cloud service whatever its cache holds, and stores no answer to it. The existing tests supplied the JA4 and HTTP/2 settings together, or the session id and sequence together, so removing one name from Constants.UNCACHED_EVIDENCE_NAMES left every test passing. - test_cloudrequestengine_cache.py tests each of the four values alone, under two spellings each (another prefix and another letter case), with no other value made for one visitor. Each request reaches the cloud service carrying the value, is not answered from a cache that holds an entry for its evidence, and leaves nothing in the cache, so the same request again reaches the cloud service too. - test_builder_cache.py in fiftyone_devicedetection_cloud builds the Device Detection Cloud Pipeline Builder with its defaults, the JavaScript builder included, and a cache. Three identical requests each reach the cloud service, because the sequence element gives every request a session id and a sequence, and the cache stays empty. Each new test fails when its name is removed from the list. The builder test fails when both the session id and the sequence are removed, as either one alone still sends the request to the cloud service. --- .../tests/test_builder_cache.py | 13 ++++ .../tests/test_cloudrequestengine_cache.py | 74 ++++++++++++++++++- 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py b/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py index 7630558a..791d8656 100644 --- a/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py +++ b/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py @@ -112,6 +112,19 @@ def test_the_same_user_agent_again_is_answered_from_the_cache(self): self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) self.assertEqual(2, cloud.data_requests) + def test_with_the_javascript_builder_each_request_reaches_the_cloud(self): + # The builder's defaults add the sequence element, which gives every + # request a session id and a sequence, so the Cloud Request Engine + # sends each request to the cloud service and stores no answer. + cloud = StandInCloud() + cache = LRUEngineCache() + pipeline = self.pipeline(cloud, cache) + + for _ in range(3): + self.assertEqual(IPHONE, self.browser_name(pipeline, IPHONE)) + self.assertEqual(3, cloud.data_requests) + self.assertEqual(0, len(cache.cache)) + if __name__ == "__main__": unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py index 08c8a298..04025718 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -24,7 +24,8 @@ A cache never stores or serves a Cloud Request Engine response made for one visitor. That is a response holding a 51Did, being a top-level member named fodid in any case, a sealed Human Confidence result, or the browser tests' -script. +script, and a response to a request carrying a session id, a sequence, a JA4 +or HTTP/2 settings, under any prefix in any letter case. """ import json @@ -47,6 +48,17 @@ # The browser tests' script the page runs. SCRIPT = "(function(){/* the browser tests */})();" +# The values that make a request one made for one visitor, by the name the +# cloud service gets each under. The service lists none of them among its +# evidence keys, so a request carrying one has the same cache key as one +# carrying only the User-Agent. +PER_VISITOR_VALUES = { + "session-id": "6f0c1a52-3d4e-4b8a-9c27-5e1f0a3b7d64", + "sequence": "2", + "ja4": "t13d1516h2_8daaf6152771_02713d6af862", + "h2": "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p", +} + def human_confidence(value, source): """A response holding HumanConfidence and HumanConfidenceSource under @@ -102,12 +114,15 @@ def pipeline_for(self, client, cache): self.addCleanup(pipeline.close) return engine, pipeline - def answer_for(self, pipeline): - """One request through the pipeline. Gives the response text the - request ended with.""" + def answer_for(self, pipeline, extra=()): + """One request through the pipeline, with the evidence in extra + beside the User-Agent. Gives the response text the request ended + with.""" data = pipeline.create_flowdata() data.evidence.add("query.User-Agent", "iPhone") + for key, value in extra: + data.evidence.add(key, value) data.process() return data.get("cloud").get("cloud") @@ -248,3 +263,54 @@ def test_a_response_without_the_browser_tests_script_is_cached(self): "browsertestsjavascript": value, "browsertestsjavascriptnullreason": "Not covered."}}) self.assertEqual(1, self.requests_for(answer), repr(value)) + + def assert_sent_and_never_cached(self, name, keys): + """A request carrying the value PER_VISITOR_VALUES gives for name, + under each of the keys in turn and with no other value made for one + visitor, goes to the cloud service carrying it. The request is not + answered from a cache that holds an entry for its evidence, and its + answer is not stored, so the same request again goes to the cloud + service too.""" + + value = PER_VISITOR_VALUES[name] + answer = json.dumps({"device": {"ismobile": False}}) + for key in keys: + with self.subTest(key=key): + extra = ((key, value),) + + client = CountingClient(answer) + cache = AlwaysHitCache() + engine, pipeline = self.pipeline_for(client, cache) + cache.entry = AspectDataDictionary(engine, { + "cloud": json.dumps({"device": {"ismobile": True}})}) + self.assertEqual(answer, self.answer_for(pipeline, extra)) + self.assertEqual(1, client.data_requests) + body = [content for (_, url, content) in client.requests + if "resource_key.json" in url][0] + self.assertEqual(value, body[key.partition(".")[2]]) + self.assertEqual( + {name}, + {sent.lower() for sent in body} & set(PER_VISITOR_VALUES)) + + client = CountingClient(answer) + cache = BasicDictionaryCache() + _, pipeline = self.pipeline_for(client, cache) + for _ in range(2): + self.assertEqual( + answer, self.answer_for(pipeline, extra)) + self.assertEqual(2, client.data_requests) + self.assertEqual({}, cache.cache) + + def test_a_session_id_alone_is_sent_and_never_cached(self): + self.assert_sent_and_never_cached( + "session-id", ("query.session-id", "cookie.Session-Id")) + + def test_a_sequence_alone_is_sent_and_never_cached(self): + self.assert_sent_and_never_cached( + "sequence", ("query.sequence", "header.SEQUENCE")) + + def test_a_ja4_alone_is_sent_and_never_cached(self): + self.assert_sent_and_never_cached("ja4", ("query.ja4", "header.JA4")) + + def test_http2_settings_alone_are_sent_and_never_cached(self): + self.assert_sent_and_never_cached("h2", ("query.h2", "server.H2")) From 96f6bb686a69e9ae22c694867f8f2a3aaff1eeb7 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:11:06 +0000 Subject: [PATCH 2/7] Key the Cloud Request Engine's cache on every 51D_ query and cookie value A page's scripts send their answers under a name that starts 51D_ and changes with each script, so the cloud service lists none of them among its evidence keys. The engine's cache key was made from the listed keys alone, so a request carrying answers but no session id, sequence, JA4 or HTTP/2 settings (with add_sequence_element off, or from a caller's own route) was answered from the cache with the response to other answers, and its own answers never reached the cloud service. The engine now accepts, beside the keys the service lists, every query or cookie value whose name starts 51D_ in any letter case, the bare name 51D_ included, as the Rust Cloud Request Engine does. CloudEvidenceKeyFilter adds the answers to the listed keys, and its list still holds the listed keys alone, because the answers have no names to list, so the Vary header the web integration writes is unchanged. What the engine sends is unchanged too, as it already sent every evidence value. Being accepted evidence, the answers are now part of the ETag of the web integration's client-side responses, which changes with them. Tests in test_cloudrequestengine_cache.py, each failing before this change: - Two requests that differ only in a 51D_ value, under four spellings, each reach the cloud service and get their own answer, and the same value again is answered from the cache. - The filter accepts the 51D_ query and cookie names and refuses a header, a server value, a name that only contains 51D_, a key with no prefix and a name whose first character is not ASCII. test_discovery_at_build.py now watches CloudEvidenceKeyFilter, the class the engine makes, to show a second request makes no filter. --- .../cloudrequestengine.py | 59 ++++++++++++++---- .../constants.py | 8 +++ .../tests/test_cloudrequestengine_cache.py | 62 ++++++++++++++++++- .../tests/test_discovery_at_build.py | 6 +- 4 files changed, 117 insertions(+), 18 deletions(-) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py index 3f2e71e1..fdb61810 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py @@ -116,6 +116,38 @@ def _mark_request_made(error): pass +def is_answer_key(key): + + """! + Whether an evidence key is a page script's answer, being a query or + cookie value whose name starts with 51D_ in any letter case, the bare + name 51D_ included. + """ + + prefix, separator, name = str(key).partition( + Constants.EVIDENCE_SEPERATOR) + start = name[:len(Constants.ANSWER_NAME_START)] + return (separator != "" + and prefix.lower() in Constants.ANSWER_PREFIXES + and start.isascii() + and start.lower() == Constants.ANSWER_NAME_START) + + +class CloudEvidenceKeyFilter(BasicListEvidenceKeyFilter): + + """! + The evidence the Cloud Request Engine accepts, being the keys the cloud + service lists and every page script's answer, as is_answer_key says. + Accepting the answers puts them in the cache key, so two requests that + differ only in an answer never share a cached response. The answers have + no names to list, so list holds the listed keys alone. + """ + + def filter_evidence_key(self, key): + + return super().filter_evidence_key(key) or is_answer_key(key) + + # Engine that makes a call to the 51Degrees cloud service. It gives the raw # JSON as its "cloud" property, read under the "cloud-response" key, or # under the deprecated key "cloud". @@ -557,24 +589,25 @@ def get_evidence_keys(self): def get_evidence_key_filter(self): """! - Instance of EvidenceKeyFilter based on evidence_keys. If the - constructor could not fetch them, this asks the cloud service again - and raises if it fails again, so that processing reports the - failure rather than using a filter that accepts nothing. + Instance of EvidenceKeyFilter based on evidence_keys, which also + accepts every page script's answer, as CloudEvidenceKeyFilter says. + If the constructor could not fetch the keys, this asks the cloud + service again and raises if it fails again, so that processing + reports the failure rather than using a filter that accepts nothing. The filter is kept, as it is asked for once for each evidence key of every request. It is made again only when evidence_keys holds another list. - @type: BasicListEvidenceKeyFilter - @return: Returns BasicListEvidenceKeyFilter + @type: CloudEvidenceKeyFilter + @return: Returns CloudEvidenceKeyFilter """ keys = self.evidence_keys kept = self._evidence_key_filter if kept is None or kept[0] is not keys: - kept = (keys, BasicListEvidenceKeyFilter(keys)) + kept = (keys, CloudEvidenceKeyFilter(keys)) self._evidence_key_filter = kept return kept[1] @@ -968,12 +1001,12 @@ def bypasses_cache(evidence): holds, and its answer is not stored. A page iteration carries the session id and the sequence, and a server may supply the visitor's JA4 and HTTP/2 settings, so a request carrying any of them is made - for one visitor. The cache key is made from the evidence keys the - service lists, but the engine sends every evidence value, and the - service lists neither the session id nor the sequence. Two - iterations of one page that differ only in those would share a key, - and the later one, which may carry the browser test answers, would - be answered from the cache and never reach the service. So a + for one visitor. The cache key is made from the evidence the engine + accepts, being the keys the service lists and the page scripts' + answers, but the engine sends every evidence value, and the service + lists neither the session id nor the sequence. Two iterations of one + page that differ only in those would share a key, and the later one + would be answered from the cache and never reach the service. So a request carrying any of Constants.UNCACHED_EVIDENCE_NAMES, under any prefix and in any letter case, bypasses the cache, and every other request is cached as before. diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py index 294ce704..01d2e1a0 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py @@ -152,6 +152,14 @@ class Constants: # CloudRequestEngine.bypasses_cache. UNCACHED_EVIDENCE_NAMES = ("session-id", "sequence", "ja4", "h2") + # The start, in lower case, of the name a page's scripts send their + # answers under, such as the browser tests' answers, and the prefixes + # the answers arrive under. The rest of the name changes with each + # script, so the service cannot list it among its evidence keys. See + # is_answer_key in cloudrequestengine.py. + ANSWER_NAME_START = "51d_" + ANSWER_PREFIXES = ("query", "cookie") + # The members of a response that hold a value made for one visitor, # compared in any case. See CloudRequestEngine.is_cacheable. A 51Did is # a top-level member. HumanConfidence and the browser tests' script are diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py index 04025718..8d7a68bd 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -25,7 +25,9 @@ visitor. That is a response holding a 51Did, being a top-level member named fodid in any case, a sealed Human Confidence result, or the browser tests' script, and a response to a request carrying a session id, a sequence, a JA4 -or HTTP/2 settings, under any prefix in any letter case. +or HTTP/2 settings, under any prefix in any letter case. The cache key holds +every query and cookie value whose name starts 51D_, so two requests that +differ only in one share no answer. """ import json @@ -87,6 +89,25 @@ def request(self, type, url, content, originHeader): return response +class AnswerEchoingClient(MockRequestClient): + """Answers every data request with the value it carried under one name + as the device value, and counts them.""" + + def __init__(self, name): + super(AnswerEchoingClient, self).__init__() + self.name = name + self.data_requests = 0 + + def request(self, type, url, content, originHeader): + response = super(AnswerEchoingClient, self).request( + type, url, content, originHeader) + if "resource_key.json" in url: + self.data_requests += 1 + response.text = json.dumps( + {"device": {"value": content.get(self.name)}}) + return response + + class AlwaysHitCache(BasicDictionaryCache): """Answers every lookup with the one entry it holds, so that a reader reaches an entry the engine never stored itself.""" @@ -314,3 +335,42 @@ def test_a_ja4_alone_is_sent_and_never_cached(self): def test_http2_settings_alone_are_sent_and_never_cached(self): self.assert_sent_and_never_cached("h2", ("query.h2", "server.H2")) + + def test_a_51d_query_or_cookie_value_is_part_of_the_cache_key(self): + """A page's scripts send their answers under a name that starts + 51D_ and changes with each script, so the cloud service lists none + of them among its evidence keys. Two requests that differ only in + such a value each reach the cloud service and get their own answer, + and the same value again is answered from the cache.""" + + for key in ("query.51D_k3Jq9xT", "cookie.51d_Pos_m8Rt", "Query.51D_", + "COOKIE.51D_x"): + with self.subTest(key=key): + client = AnswerEchoingClient(key.partition(".")[2]) + _, pipeline = self.pipeline_for( + client, BasicDictionaryCache()) + answers = [ + json.loads(self.answer_for( + pipeline, ((key, value),)))["device"]["value"] + for value in ("first", "second", "first")] + self.assertEqual(["first", "second", "first"], answers) + self.assertEqual(2, client.data_requests) + + def test_the_engine_accepts_every_51d_query_and_cookie_value(self): + """The engine accepts a query or cookie value whose name starts + 51D_, in any letter case, the bare name 51D_ included, beside the + evidence keys the cloud service lists. The answers have no names to + list, so the filter's list holds the listed keys alone.""" + + engine, _ = self.pipeline_for( + MockRequestClient(), BasicDictionaryCache()) + key_filter = engine.get_evidence_key_filter() + for key in ("query.51d_q7hx2b", "cookie.51d_browsertests", + "Query.51D_Q7Hx2b", "COOKIE.51D_x", "query.51d_", + "cookie.51D_", "query.User-Agent"): + self.assertTrue(key_filter.filter_evidence_key(key), key) + for key in ("query.51d", "header.51d_q7hx2b", "server.51d_q7hx2b", + "query.x51d_q7hx2b", "query.51dq7hx2b", "51d_q7hx2b", + "query.é1d_q7hx2b", "query.other"): + self.assertFalse(key_filter.filter_evidence_key(key), key) + self.assertEqual(["query.user-agent"], key_filter.list) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_discovery_at_build.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_discovery_at_build.py index 7e160b53..1694f74e 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_discovery_at_build.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_discovery_at_build.py @@ -44,8 +44,6 @@ from fiftyone_pipeline_cloudrequestengine.cloudrequestexception import \ CloudRequestException from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient -from fiftyone_pipeline_core.basiclist_evidence_keyfilter import \ - BasicListEvidenceKeyFilter from fiftyone_pipeline_core.logger import Logger from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder @@ -378,8 +376,8 @@ def test_a_second_request_makes_no_filter(self): self.assertEqual({}, process(pipeline).errors) with patch.object( - cloudrequestengine, "BasicListEvidenceKeyFilter", - wraps=BasicListEvidenceKeyFilter) as made: + cloudrequestengine, "CloudEvidenceKeyFilter", + wraps=cloudrequestengine.CloudEvidenceKeyFilter) as made: data = process(pipeline) self.assertEqual({}, data.errors) From 40f504faa48c4f7e45a8cf2e939f845c031eef6b Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:12:48 +0000 Subject: [PATCH 3/7] TEST: Check the server route sends 51D_ values unchanged on the wire The server route test checked the dictionary MockRequestClient records, and its 51D_ values held no character a form body encodes, so it could not show the values reach the cloud service unchanged. - The posted answer and the cookie answer now carry +, %, =, a space and characters outside ASCII, through the Flask application and the web integration as before. - WireClient answers as MockRequestClient does and also gives every request to RequestClient, the client the engine uses by default, with the network replaced, keeping the URL, the content type and the body it would send. - The test checks each data request's body is a form body of ASCII text, that reading it as the cloud service does (UTF-8) gives back each answer, the cookie answer and the session id exactly, once each, and that each value is form encoded, with + as %2B, % as %25, = as %3D, a space as + and each byte of the UTF-8 of a character outside ASCII percent encoded. The test fails if RequestClient joins the body without encoding it, and if the engine decodes a value before sending it. --- .../tests/test_server_route_pass_through.py | 92 ++++++++++++++++++- 1 file changed, 87 insertions(+), 5 deletions(-) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py index aa5c02bf..2d4c0500 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py @@ -33,11 +33,15 @@ import unittest import warnings from unittest import mock +from urllib.parse import parse_qs +import requests from flask import Flask, request +from requests.adapters import HTTPAdapter from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ CloudRequestEngine +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_core import web from fiftyone_pipeline_core.web import javascript_response, json_response @@ -57,17 +61,52 @@ # Browser test answers are sent under a name that starts 51D_ and changes # with each script, and their value starts with a schema and a bar. Real -# answers are long, so one here is too. +# answers are long, so one here is too. Both values carry the characters a +# form body encodes, being +, %, =, a space and characters outside ASCII, +# so the tests show each one reaches the cloud unchanged. ANSWER_NAME = "51D_k3Jq9xT" -ANSWER_VALUE = "3z|" + "aB0-_" * 12000 +ANSWER_VALUE = "3z|a+b%2Bc=d eé€|" + "aB0-_" * 12000 # A value a snippet stored as a cookie, which the script does not post. COOKIE_NAME = "51D_Pos_m8Rt" -COOKIE_VALUE = "3|cookie-answer" +COOKIE_VALUE = "3|cookie+answer%2B=x yé€" + +# The content type of a form body, which the cloud service reads as UTF-8. +FORM_CONTENT_TYPE = "application/x-www-form-urlencoded" SESSION_ID = re.compile(r'var sessionId = "([^"]*)";') SEQUENCE = re.compile(r"var sequence = ([0-9]+);") +class WireClient(MockRequestClient): + """Answers as MockRequestClient does, and also gives every request to + RequestClient, the client the engine uses by default, with the network + replaced, keeping the URL, the content type and the body it would have + sent.""" + + def __init__(self): + super(WireClient, self).__init__() + self.sent = [] + + def request(self, type, url, content, originHeader): + answer = super(WireClient, self).request( + type, url, content, originHeader) + + def send(adapter, prepared, **kwargs): + self.sent.append((prepared.url, + prepared.headers.get("Content-Type"), + prepared.body)) + response = requests.Response() + response.status_code = answer.status_code + response._content = answer.content + response.url = prepared.url + response.request = prepared + return response + + with mock.patch.object(HTTPAdapter, "send", send): + RequestClient().request(type, url, content, originHeader) + return answer + + def make_app(engine, supply_connection): """A Flask application serving the pipeline's JavaScript and the JSON endpoint the JavaScript posts to. Where supply_connection is set, the @@ -110,7 +149,7 @@ def results(): class ServerRoutePassThroughTests(unittest.TestCase): def setUp(self): - self.http = MockRequestClient() + self.http = WireClient() self.engine = CloudRequestEngine({ "resource_key": "resource_key", "http_client": self.http, @@ -121,6 +160,29 @@ def data_requests(self): return [content for (_, url, content) in self.http.requests if "resource_key.json" in url] + def wire_bodies(self): + """The body RequestClient would have sent with every data request, + in order, as the text that goes on the wire. Each is checked to be + a form body, which the cloud service reads as UTF-8.""" + + bodies = [] + for url, content_type, body in self.http.sent: + if "resource_key.json" in url: + self.assertEqual(FORM_CONTENT_TYPE, content_type) + self.assertIsInstance(body, str) + # Every character outside ASCII is percent encoded. + self.assertTrue(body.isascii()) + bodies.append(body) + return bodies + + @staticmethod + def read_form(body): + """A form body read as the cloud service reads it, as each name with + every value it was given.""" + + return parse_qs(body, keep_blank_values=True, strict_parsing=True, + encoding="utf-8", errors="strict") + def script_values(self, response): """The session id and the sequence the script was written with.""" text = response.get_data(as_text=True) @@ -155,7 +217,9 @@ def run_iterations(self, client): def test_session_id_sequence_and_answers_reach_the_cloud(self): """Every iteration sends the cloud the session id the script was written with, a sequence one more than the iteration before, and - the answers the page posted and stored as cookies, unchanged.""" + the answers the page posted and stored as cookies, unchanged. That + is checked in the body RequestClient would send, which the cloud + service reads back to the values the page gave.""" session_id = self.run_iterations(make_app(self.engine, False)) bodies = self.data_requests() @@ -172,6 +236,24 @@ def test_session_id_sequence_and_answers_reach_the_cloud(self): self.assertEqual(COOKIE_VALUE, body[COOKIE_NAME]) self.assertNotIn(ANSWER_NAME, bodies[0]) + sent = self.wire_bodies() + self.assertEqual(3, len(sent)) + for body in sent[1:]: + form = self.read_form(body) + self.assertEqual([ANSWER_VALUE], form[ANSWER_NAME]) + self.assertEqual([COOKIE_VALUE], form[COOKIE_NAME]) + self.assertEqual([session_id], form["session-id"]) + # The form encoding of each value, with + as %2B, % as %25, = + # as %3D, a space as + and each byte of the UTF-8 of a + # character outside ASCII percent encoded. + self.assertIn( + ANSWER_NAME + "=3z%7Ca%2Bb%252Bc%3Dd+e%C3%A9%E2%82%AC%7CaB0", + body) + self.assertIn( + COOKIE_NAME + "=3%7Ccookie%2Banswer%252B%3Dx+y%C3%A9%E2%82%AC", + body) + self.assertNotIn(ANSWER_NAME, self.read_form(sent[0])) + def test_the_server_supplies_the_visitors_connection(self): """A server supplies the visitor's IP address, JA4 and H2 as query evidence, and the cloud gets them on every iteration under the From 7a018ecf8a95ac78d36caf3de27f2728297fbfa5 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:14:26 +0000 Subject: [PATCH 4/7] Make LRUEngineCache safe to share between threads One LRUEngineCache is shared by every request an engine processes, and a web server processes requests on several threads at once. The cachetools LRUCache underneath changes its order on every read and removes the least recently used entry on a write when full, with nothing holding threads apart, so concurrent requests could raise KeyError or "OrderedDict mutated during iteration" from inside the cache, or leave it inconsistent. get_cache_value and set_cache_value now hold a threading.Lock while they read or write the LRUCache, so one thread at a time is inside it. test_lru_cache.py in fiftyone_pipeline_engines, both failing without the lock on three runs out of three: - Eight threads read and write one cache whose LRUCache pauses in each call and records how many threads are inside it at once, which is one. - Eight threads make 3,000 reads and writes each on one cache of 8 entries over 32 keys, with the interpreter switching threads every microsecond. No thread raises, every read gives the value written for its key or nothing, the cache holds no more than 8 entries, and it still evicts the least recently used entry afterwards. --- .../fiftyone_pipeline_engines/lru_cache.py | 15 +- .../tests/test_lru_cache.py | 168 ++++++++++++++++++ 2 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py diff --git a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/lru_cache.py b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/lru_cache.py index 4ee6984a..43208946 100644 --- a/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/lru_cache.py +++ b/pipeline/fiftyone_pipeline_engines/src/fiftyone_pipeline_engines/lru_cache.py @@ -20,13 +20,18 @@ # such notice(s) shall fulfill the requirements of that article. # ********************************************************************* +import threading + from .datakeyed_cache import DataKeyedCache from cachetools import LRUCache class LRUEngineCache(DataKeyedCache): """! - An instance of DataKeyed cache using a least recently used (LRU) method + An instance of DataKeyed cache using a least recently used (LRU) method. + A read changes the order of the entries and a write may remove one, so + one thread at a time reads or writes the cache, which lets requests + processed on several threads share it. """ def __init__(self, size = 1000): """! @@ -36,10 +41,14 @@ def __init__(self, size = 1000): """ self.cache = LRUCache(maxsize=size) + self._lock = threading.Lock() def get_cache_value (self, cache_key): - return self.cache.get(cache_key) + with self._lock: + return self.cache.get(cache_key) def set_cache_value(self, key, value): - self.cache.__setitem__(key, value) + + with self._lock: + self.cache[key] = value diff --git a/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py b/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py new file mode 100644 index 00000000..4788c52b --- /dev/null +++ b/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py @@ -0,0 +1,168 @@ +# ********************************************************************* +# 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. +# ********************************************************************* + +""" +One LRUEngineCache is shared by every request an engine processes, and a +web server processes requests on several threads at once. A least recently +used cache changes its order on every read, so the cache lets one thread at +a time read or write it. +""" + +import sys +import threading +import time +import unittest + +from cachetools import LRUCache + +from fiftyone_pipeline_engines.lru_cache import LRUEngineCache + +# How many threads share the cache, and how many reads and writes each makes. +THREADS = 8 +OPERATIONS_PER_THREAD = 3000 + +# The cache holds fewer entries than the keys used, so writes keep removing +# the least recently used entry while other threads read. +CACHE_SIZE = 8 +KEYS = 32 + +# How long each call to the recording cache below pauses, so that two +# threads the cache does not hold apart are inside it at once. +PAUSE_SECONDS = 0.001 +CALLS_PER_THREAD = 10 + +# How often, in seconds, the interpreter lets another thread run, made short +# while the threads run so that their reads and writes interleave closely. +SWITCH_INTERVAL_SECONDS = 1e-6 + + +def value_of(key): + return "value of " + str(key) + + +class OverlapRecordingCache(LRUCache): + """An LRUCache that records the most threads inside its get and its + __setitem__ at once, pausing in each.""" + + def __init__(self, maxsize): + super().__init__(maxsize) + self.inside = 0 + self.most_inside = 0 + self.counting = threading.Lock() + + def enter(self): + with self.counting: + self.inside += 1 + self.most_inside = max(self.most_inside, self.inside) + time.sleep(PAUSE_SECONDS) + + def leave(self): + with self.counting: + self.inside -= 1 + + def get(self, key, default=None): + self.enter() + try: + return super().get(key, default) + finally: + self.leave() + + def __setitem__(self, key, value): + self.enter() + try: + super().__setitem__(key, value) + finally: + self.leave() + + +def run_threads(work): + """Runs work on THREADS threads at once, started together. Gives every + exception a thread raised.""" + + start = threading.Barrier(THREADS) + errors = [] + + def run(number): + start.wait() + try: + work(number) + except Exception as error: + errors.append(error) + + threads = [threading.Thread(target=run, args=(number,)) + for number in range(THREADS)] + interval = sys.getswitchinterval() + sys.setswitchinterval(SWITCH_INTERVAL_SECONDS) + try: + for thread in threads: + thread.start() + for thread in threads: + thread.join() + finally: + sys.setswitchinterval(interval) + return errors + + +class LRUEngineCacheThreadTests(unittest.TestCase): + + def test_one_thread_at_a_time_reads_or_writes_the_cache(self): + cache = LRUEngineCache(CACHE_SIZE) + recording = OverlapRecordingCache(CACHE_SIZE) + cache.cache = recording + + def work(number): + for call in range(CALLS_PER_THREAD): + key = (number + call) % KEYS + cache.set_cache_value(key, value_of(key)) + cache.get_cache_value(key) + + self.assertEqual([], run_threads(work)) + self.assertEqual(1, recording.most_inside) + + def test_threads_hammering_one_cache_read_back_what_was_written(self): + cache = LRUEngineCache(CACHE_SIZE) + wrong = [] + + def work(number): + for operation in range(OPERATIONS_PER_THREAD): + key = (number * 7 + operation) % KEYS + if operation % 2 == 0: + cache.set_cache_value(key, value_of(key)) + else: + found = cache.get_cache_value(key) + if found is not None and found != value_of(key): + wrong.append((key, found)) + + self.assertEqual([], run_threads(work)) + self.assertEqual([], wrong) + self.assertLessEqual(len(cache.cache), CACHE_SIZE) + + # The cache still works as a least recently used cache afterwards. + for key in range(KEYS): + cache.set_cache_value(key, value_of(key)) + self.assertEqual(CACHE_SIZE, len(cache.cache)) + self.assertEqual(value_of(KEYS - 1), cache.get_cache_value(KEYS - 1)) + self.assertIsNone(cache.get_cache_value(0)) + + +if __name__ == "__main__": + unittest.main() From d26c2c9660c1582501f89d0e26420aa07c9febbc Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:15:05 +0000 Subject: [PATCH 5/7] TEST: Restore LF line endings in the object name tests test_javascriptbuilder_object_name.py had LF line endings until the change that kept two blank lines before _declared_names, which also turned every line ending to CRLF, so that change showed as all 350 lines rewritten. The file has LF line endings again, as every other Python file here does. With white space ignored, the file differs from its version before the Node start-up change only in setUpModule and the two constants, NODE_CALL_SECONDS and NODE_START_SECONDS. Against the first commit of that change, the only difference is the blank line the second one added. --- .../test_javascriptbuilder_object_name.py | 700 +++++++++--------- 1 file changed, 350 insertions(+), 350 deletions(-) diff --git a/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py b/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py index 86ad3582..7753174a 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py @@ -1,350 +1,350 @@ -# ********************************************************************* -# 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 client side object's name can be set in the builder's settings -(obj_name) or per request (query.fod-js-object-name). The name is written -into the script as a variable name, a session storage key and a property -name, so these tests check that a different name works, and that a name -which is not a JavaScript identifier is never written into the script. - -The script is checked with "node --check" and run in Node with a minimal -stand in for a browser (object_name_harness.js). Both need Node on the path, -which every GitHub hosted runner has. -""" - -import json -import os -import re -import shutil -import subprocess -import tempfile -import unittest - -from parameterized import parameterized - -from fiftyone_pipeline_core.constants import Constants -from fiftyone_pipeline_core.javascriptbuilder import JavascriptBuilderElement -from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder - -from .classes.memorylogger import MemoryLogger -from .test_javascriptbuilder import TestEngine - -# The names the specification refuses that are not reserved words of the -# language, being eval, arguments, and the properties of the browser's Window -# object that a top level var cannot replace or that navigate the page away. -REFUSED_NAMES = [ - "eval", "arguments", "window", "document", "top", "name", "status", - "history", "navigator", "closed", "location", "frameElement", - "isSecureContext", "crossOriginIsolated", "trustedTypes", "crypto", - "indexedDB", "localStorage", "sessionStorage", "caches", "cookieStore", - "speechSynthesis", "styleMedia", "crashReport", "credentialless", - "customElements", "documentPictureInPicture", "fence", "launchQueue", - "originAgentCluster"] - -# Window properties that a top level var can replace, so the names stay -# allowed, and near misses of refused names. -ALLOWED_NAMES = [ - "self", "frames", "parent", "opener", "length", "windows", "Window", - "cachesX"] - -NODE = shutil.which("node") -HARNESS = os.path.join(os.path.dirname(__file__), "object_name_harness.js") - - -def _render(settings=None, evidence=None, logger=None): - """Render the script for one request and return it.""" - - builder = PipelineBuilder( - {"javascript_builder_settings": settings or {"minify": False}}) - if logger is not None: - builder.add_logger(logger) - pipeline = builder.add(TestEngine()).build() - flowdata = pipeline.create_flowdata() - for key, value in (evidence or {}).items(): - flowdata.evidence.add(key, value) - flowdata.process() - return flowdata.javascriptbuilder.javascript - - -def _write(script): - handle, path = tempfile.mkstemp(suffix=".js") - with os.fdopen(handle, "w", encoding="utf-8") as f: - f.write(script) - return path - - -# The longest one call to Node may take once Node has started. -NODE_CALL_SECONDS = 60 -# The longest Node's first start on a runner may take. That start can be far -# slower than any later call, so it is made once, before the tests. -NODE_START_SECONDS = 300 - - -def setUpModule(): - if NODE: - subprocess.run([NODE, "-e", "0"], capture_output=True, - timeout=NODE_START_SECONDS) - - -def _node(*args): - return subprocess.run( - [NODE] + list(args), capture_output=True, text=True, - timeout=NODE_CALL_SECONDS) - - -def _declared_names(script): - return re.findall( - r"\bvar\s+([^\s=]*)\s*=\s*new\s+fiftyoneDegreesManager\b", script) - - -@unittest.skipUnless(NODE, "Node is needed to parse and run the script") -class JavaScriptBuilderObjectNameTests(unittest.TestCase): - - def assert_parses(self, script): - path = _write(script) - try: - result = _node("--check", path) - finally: - os.remove(path) - self.assertEqual( - 0, result.returncode, - "the rendered script does not parse: " + result.stderr) - - def run_script(self, script, name): - path = _write(script) - try: - result = _node(HARNESS, path, name, "test.normal") - finally: - os.remove(path) - self.assertEqual(0, result.returncode, result.stderr) - return json.loads(result.stdout) - - def assert_uses_name(self, script, name): - self.assertEqual([name], _declared_names(script)) - self.assertIsNone( - re.search(r"\bvar\s+fod\b", script) if name != "fod" else None, - "the default name must not be declared as well") - self.assertIn('var sessionKey = "' + name + '";', script) - self.assertIn('window["' + name + 'Evidence"]', script) - self.assertIn('typeof window["' + name + '"]', script) - - @parameterized.expand([ - ["settings", {"obj_name": "myFod", "minify": False}, {}], - ["evidence", {"minify": False}, - {Constants.EVIDENCE_OBJECT_NAME: "myFod"}], - ]) - def test_valid_name_is_used(self, _, settings, evidence): - """A valid name from the settings or from the page request is - declared, used as the storage key and in the evidence lookup, and - the script parses and creates that object.""" - - script = _render(settings, evidence) - - self.assert_uses_name(script, "myFod") - self.assert_parses(script) - - result = self.run_script(script, "myFod") - self.assertIsNone(result["error"]) - self.assertTrue(result["exists"], "window.myFod was not created") - self.assertEqual("function", result["complete"]) - self.assertEqual("function", result["onChange"]) - self.assertEqual("function", result["refresh"]) - self.assertEqual("true", result["value"]) - self.assertEqual(["myFod"], result["globals"]) - - def test_valid_name_from_evidence_minified(self): - """The minified script declares the requested name and parses.""" - - script = _render( - {"minify": True}, {Constants.EVIDENCE_OBJECT_NAME: "myFod"}) - - self.assertEqual(["myFod"], _declared_names(script)) - self.assert_parses(script) - - @parameterized.expand([ - ["statement", "a;b", True], - # The name has a letter that is not a hex digit, so the random - # session id the script also carries can never contain it. - ["leading_digit", "9zz", True], - ["quote", 'x"y', True], - ["empty", "", False], - # A reserved word is also an ordinary word in the script's comments, - # so only the places the name is written are checked for it. - ["reserved_word", "class", False], - # These are also ordinary words in the script, as values or as the - # constructor's own name. - ["infinity", "Infinity", False], - ["nan", "NaN", False], - ["undefined", "undefined", False], - ["constructor_name", "fiftyoneDegreesManager", False], - ]) - def test_invalid_name_from_evidence_is_ignored( - self, _, name, check_text): - """A requested name that is not a JavaScript identifier is not - written into the script. The configured name is used, the script - parses and runs, and a warning is logged.""" - - logger = MemoryLogger("warning") - script = _render( - {"minify": False}, - {Constants.EVIDENCE_OBJECT_NAME: name}, - logger) - - self.assert_uses_name(script, "fod") - self.assert_parses(script) - - # The requested value is still one of the request's query values, - # which the script carries as data inside a JSON string. Every other - # line must be free of it. - if check_text: - other_lines = [ - line for line in script.splitlines() - if "var renderedParameters" not in line] - self.assertFalse( - any(name in line for line in other_lines), - "the requested name was written into the script") - - result = self.run_script(script, "fod") - self.assertIsNone(result["error"]) - self.assertTrue(result["exists"]) - self.assertEqual(["fod"], result["globals"]) - - warnings = [ - entry["message"] for entry in logger.memory_log - if entry["level"] == "warning" - and Constants.EVIDENCE_OBJECT_NAME in entry["message"]] - self.assertEqual(1, len(warnings), str(logger.memory_log)) - if check_text: - self.assertNotIn(name, warnings[0]) - - @parameterized.expand([[name] for name in REFUSED_NAMES]) - def test_refused_window_name_from_evidence_is_ignored(self, name): - """A requested name the specification refuses is not declared. The - configured name is used, the script parses and runs, and a warning - is logged.""" - - logger = MemoryLogger("warning") - script = _render( - {"minify": False}, - {Constants.EVIDENCE_OBJECT_NAME: name}, - logger) - - self.assert_uses_name(script, "fod") - self.assert_parses(script) - - result = self.run_script(script, "fod") - self.assertIsNone(result["error"]) - self.assertTrue(result["exists"]) - self.assertEqual(["fod"], result["globals"]) - - warnings = [ - entry["message"] for entry in logger.memory_log - if entry["level"] == "warning" - and Constants.EVIDENCE_OBJECT_NAME in entry["message"]] - self.assertEqual(1, len(warnings), str(logger.memory_log)) - - @parameterized.expand([[name] for name in ALLOWED_NAMES]) - def test_allowed_window_name_from_evidence_is_used(self, name): - """A name the specification allows is declared and the script - parses.""" - - logger = MemoryLogger("warning") - script = _render( - {"minify": False}, - {Constants.EVIDENCE_OBJECT_NAME: name}, - logger) - - self.assert_uses_name(script, name) - self.assert_parses(script) - self.assertEqual([], [ - entry for entry in logger.memory_log - if entry["level"] == "warning" - and Constants.EVIDENCE_OBJECT_NAME in entry["message"]]) - - def test_invalid_name_from_evidence_uses_configured_name(self): - """The fallback is the configured name, not always 'fod'.""" - - script = _render( - {"obj_name": "myFod", "minify": False}, - {Constants.EVIDENCE_OBJECT_NAME: "9bad"}) - - self.assert_uses_name(script, "myFod") - self.assert_parses(script) - - -class JavaScriptBuilderObjectNameSettingTests(unittest.TestCase): - - @parameterized.expand([ - ["statement", "a;b"], - ["leading_digit", "9bad"], - ["quote", 'x"y'], - ["empty", ""], - ["reserved_word", "var"], - ["infinity", "Infinity"], - ["nan", "NaN"], - ["undefined", "undefined"], - ["constructor_name", "fiftyoneDegreesManager"], - ["trailing_new_line", "fod\n"], - ["not_ascii", "caf\u00e9"], - ["not_a_string", 5], - ]) - def test_invalid_configured_name_is_refused(self, _, name): - """An invalid name in the settings is refused when the builder is - created.""" - - with self.assertRaises(ValueError): - JavascriptBuilderElement({"obj_name": name}) - - @parameterized.expand([[name] for name in REFUSED_NAMES]) - def test_refused_window_name_is_refused(self, name): - """A name the specification refuses is refused when the builder is - created.""" - - with self.assertRaises(ValueError): - JavascriptBuilderElement({"obj_name": name}) - - @parameterized.expand([[name] for name in ALLOWED_NAMES]) - def test_allowed_window_name_is_accepted(self, name): - element = JavascriptBuilderElement({"obj_name": name}) - self.assertEqual(name, element.settings["_objName"]) - - @parameterized.expand([ - ["plain", "myFod"], - ["underscore", "_fod"], - ["dollar", "$fod9"], - ["contains_a_reserved_word", "classy"], - ]) - def test_valid_configured_name_is_accepted(self, _, name): - element = JavascriptBuilderElement({"obj_name": name}) - self.assertEqual(name, element.settings["_objName"]) - - @parameterized.expand([ - ["absent", {}], - ["none", {"obj_name": None}], - ]) - def test_name_not_configured_is_fod(self, _, settings): - """A name that is not configured at all, absent or None, means fod. - Only a configured name, the empty string included, is checked.""" - - element = JavascriptBuilderElement(settings) - self.assertEqual("fod", element.settings["_objName"]) +# ********************************************************************* +# 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 client side object's name can be set in the builder's settings +(obj_name) or per request (query.fod-js-object-name). The name is written +into the script as a variable name, a session storage key and a property +name, so these tests check that a different name works, and that a name +which is not a JavaScript identifier is never written into the script. + +The script is checked with "node --check" and run in Node with a minimal +stand in for a browser (object_name_harness.js). Both need Node on the path, +which every GitHub hosted runner has. +""" + +import json +import os +import re +import shutil +import subprocess +import tempfile +import unittest + +from parameterized import parameterized + +from fiftyone_pipeline_core.constants import Constants +from fiftyone_pipeline_core.javascriptbuilder import JavascriptBuilderElement +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder + +from .classes.memorylogger import MemoryLogger +from .test_javascriptbuilder import TestEngine + +# The names the specification refuses that are not reserved words of the +# language, being eval, arguments, and the properties of the browser's Window +# object that a top level var cannot replace or that navigate the page away. +REFUSED_NAMES = [ + "eval", "arguments", "window", "document", "top", "name", "status", + "history", "navigator", "closed", "location", "frameElement", + "isSecureContext", "crossOriginIsolated", "trustedTypes", "crypto", + "indexedDB", "localStorage", "sessionStorage", "caches", "cookieStore", + "speechSynthesis", "styleMedia", "crashReport", "credentialless", + "customElements", "documentPictureInPicture", "fence", "launchQueue", + "originAgentCluster"] + +# Window properties that a top level var can replace, so the names stay +# allowed, and near misses of refused names. +ALLOWED_NAMES = [ + "self", "frames", "parent", "opener", "length", "windows", "Window", + "cachesX"] + +NODE = shutil.which("node") +HARNESS = os.path.join(os.path.dirname(__file__), "object_name_harness.js") + + +def _render(settings=None, evidence=None, logger=None): + """Render the script for one request and return it.""" + + builder = PipelineBuilder( + {"javascript_builder_settings": settings or {"minify": False}}) + if logger is not None: + builder.add_logger(logger) + pipeline = builder.add(TestEngine()).build() + flowdata = pipeline.create_flowdata() + for key, value in (evidence or {}).items(): + flowdata.evidence.add(key, value) + flowdata.process() + return flowdata.javascriptbuilder.javascript + + +def _write(script): + handle, path = tempfile.mkstemp(suffix=".js") + with os.fdopen(handle, "w", encoding="utf-8") as f: + f.write(script) + return path + + +# The longest one call to Node may take once Node has started. +NODE_CALL_SECONDS = 60 +# The longest Node's first start on a runner may take. That start can be far +# slower than any later call, so it is made once, before the tests. +NODE_START_SECONDS = 300 + + +def setUpModule(): + if NODE: + subprocess.run([NODE, "-e", "0"], capture_output=True, + timeout=NODE_START_SECONDS) + + +def _node(*args): + return subprocess.run( + [NODE] + list(args), capture_output=True, text=True, + timeout=NODE_CALL_SECONDS) + + +def _declared_names(script): + return re.findall( + r"\bvar\s+([^\s=]*)\s*=\s*new\s+fiftyoneDegreesManager\b", script) + + +@unittest.skipUnless(NODE, "Node is needed to parse and run the script") +class JavaScriptBuilderObjectNameTests(unittest.TestCase): + + def assert_parses(self, script): + path = _write(script) + try: + result = _node("--check", path) + finally: + os.remove(path) + self.assertEqual( + 0, result.returncode, + "the rendered script does not parse: " + result.stderr) + + def run_script(self, script, name): + path = _write(script) + try: + result = _node(HARNESS, path, name, "test.normal") + finally: + os.remove(path) + self.assertEqual(0, result.returncode, result.stderr) + return json.loads(result.stdout) + + def assert_uses_name(self, script, name): + self.assertEqual([name], _declared_names(script)) + self.assertIsNone( + re.search(r"\bvar\s+fod\b", script) if name != "fod" else None, + "the default name must not be declared as well") + self.assertIn('var sessionKey = "' + name + '";', script) + self.assertIn('window["' + name + 'Evidence"]', script) + self.assertIn('typeof window["' + name + '"]', script) + + @parameterized.expand([ + ["settings", {"obj_name": "myFod", "minify": False}, {}], + ["evidence", {"minify": False}, + {Constants.EVIDENCE_OBJECT_NAME: "myFod"}], + ]) + def test_valid_name_is_used(self, _, settings, evidence): + """A valid name from the settings or from the page request is + declared, used as the storage key and in the evidence lookup, and + the script parses and creates that object.""" + + script = _render(settings, evidence) + + self.assert_uses_name(script, "myFod") + self.assert_parses(script) + + result = self.run_script(script, "myFod") + self.assertIsNone(result["error"]) + self.assertTrue(result["exists"], "window.myFod was not created") + self.assertEqual("function", result["complete"]) + self.assertEqual("function", result["onChange"]) + self.assertEqual("function", result["refresh"]) + self.assertEqual("true", result["value"]) + self.assertEqual(["myFod"], result["globals"]) + + def test_valid_name_from_evidence_minified(self): + """The minified script declares the requested name and parses.""" + + script = _render( + {"minify": True}, {Constants.EVIDENCE_OBJECT_NAME: "myFod"}) + + self.assertEqual(["myFod"], _declared_names(script)) + self.assert_parses(script) + + @parameterized.expand([ + ["statement", "a;b", True], + # The name has a letter that is not a hex digit, so the random + # session id the script also carries can never contain it. + ["leading_digit", "9zz", True], + ["quote", 'x"y', True], + ["empty", "", False], + # A reserved word is also an ordinary word in the script's comments, + # so only the places the name is written are checked for it. + ["reserved_word", "class", False], + # These are also ordinary words in the script, as values or as the + # constructor's own name. + ["infinity", "Infinity", False], + ["nan", "NaN", False], + ["undefined", "undefined", False], + ["constructor_name", "fiftyoneDegreesManager", False], + ]) + def test_invalid_name_from_evidence_is_ignored( + self, _, name, check_text): + """A requested name that is not a JavaScript identifier is not + written into the script. The configured name is used, the script + parses and runs, and a warning is logged.""" + + logger = MemoryLogger("warning") + script = _render( + {"minify": False}, + {Constants.EVIDENCE_OBJECT_NAME: name}, + logger) + + self.assert_uses_name(script, "fod") + self.assert_parses(script) + + # The requested value is still one of the request's query values, + # which the script carries as data inside a JSON string. Every other + # line must be free of it. + if check_text: + other_lines = [ + line for line in script.splitlines() + if "var renderedParameters" not in line] + self.assertFalse( + any(name in line for line in other_lines), + "the requested name was written into the script") + + result = self.run_script(script, "fod") + self.assertIsNone(result["error"]) + self.assertTrue(result["exists"]) + self.assertEqual(["fod"], result["globals"]) + + warnings = [ + entry["message"] for entry in logger.memory_log + if entry["level"] == "warning" + and Constants.EVIDENCE_OBJECT_NAME in entry["message"]] + self.assertEqual(1, len(warnings), str(logger.memory_log)) + if check_text: + self.assertNotIn(name, warnings[0]) + + @parameterized.expand([[name] for name in REFUSED_NAMES]) + def test_refused_window_name_from_evidence_is_ignored(self, name): + """A requested name the specification refuses is not declared. The + configured name is used, the script parses and runs, and a warning + is logged.""" + + logger = MemoryLogger("warning") + script = _render( + {"minify": False}, + {Constants.EVIDENCE_OBJECT_NAME: name}, + logger) + + self.assert_uses_name(script, "fod") + self.assert_parses(script) + + result = self.run_script(script, "fod") + self.assertIsNone(result["error"]) + self.assertTrue(result["exists"]) + self.assertEqual(["fod"], result["globals"]) + + warnings = [ + entry["message"] for entry in logger.memory_log + if entry["level"] == "warning" + and Constants.EVIDENCE_OBJECT_NAME in entry["message"]] + self.assertEqual(1, len(warnings), str(logger.memory_log)) + + @parameterized.expand([[name] for name in ALLOWED_NAMES]) + def test_allowed_window_name_from_evidence_is_used(self, name): + """A name the specification allows is declared and the script + parses.""" + + logger = MemoryLogger("warning") + script = _render( + {"minify": False}, + {Constants.EVIDENCE_OBJECT_NAME: name}, + logger) + + self.assert_uses_name(script, name) + self.assert_parses(script) + self.assertEqual([], [ + entry for entry in logger.memory_log + if entry["level"] == "warning" + and Constants.EVIDENCE_OBJECT_NAME in entry["message"]]) + + def test_invalid_name_from_evidence_uses_configured_name(self): + """The fallback is the configured name, not always 'fod'.""" + + script = _render( + {"obj_name": "myFod", "minify": False}, + {Constants.EVIDENCE_OBJECT_NAME: "9bad"}) + + self.assert_uses_name(script, "myFod") + self.assert_parses(script) + + +class JavaScriptBuilderObjectNameSettingTests(unittest.TestCase): + + @parameterized.expand([ + ["statement", "a;b"], + ["leading_digit", "9bad"], + ["quote", 'x"y'], + ["empty", ""], + ["reserved_word", "var"], + ["infinity", "Infinity"], + ["nan", "NaN"], + ["undefined", "undefined"], + ["constructor_name", "fiftyoneDegreesManager"], + ["trailing_new_line", "fod\n"], + ["not_ascii", "caf\u00e9"], + ["not_a_string", 5], + ]) + def test_invalid_configured_name_is_refused(self, _, name): + """An invalid name in the settings is refused when the builder is + created.""" + + with self.assertRaises(ValueError): + JavascriptBuilderElement({"obj_name": name}) + + @parameterized.expand([[name] for name in REFUSED_NAMES]) + def test_refused_window_name_is_refused(self, name): + """A name the specification refuses is refused when the builder is + created.""" + + with self.assertRaises(ValueError): + JavascriptBuilderElement({"obj_name": name}) + + @parameterized.expand([[name] for name in ALLOWED_NAMES]) + def test_allowed_window_name_is_accepted(self, name): + element = JavascriptBuilderElement({"obj_name": name}) + self.assertEqual(name, element.settings["_objName"]) + + @parameterized.expand([ + ["plain", "myFod"], + ["underscore", "_fod"], + ["dollar", "$fod9"], + ["contains_a_reserved_word", "classy"], + ]) + def test_valid_configured_name_is_accepted(self, _, name): + element = JavascriptBuilderElement({"obj_name": name}) + self.assertEqual(name, element.settings["_objName"]) + + @parameterized.expand([ + ["absent", {}], + ["none", {"obj_name": None}], + ]) + def test_name_not_configured_is_fod(self, _, settings): + """A name that is not configured at all, absent or None, means fod. + Only a configured name, the empty string included, is checked.""" + + element = JavascriptBuilderElement(settings) + self.assertEqual("fod", element.settings["_objName"]) From b7fda593f1c5513af291865b7316df74e946083d Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:21:37 +0000 Subject: [PATCH 6/7] BUILD: Wait for the version a publish released before testing the examples After a run of Publish or Nightly Pipeline, the Examples vs Published Packages workflow pinned each package to what PyPI's JSON gave as its latest version at that moment, which straight after an upload can still be the version before, so the examples could be tested against the previous release with nothing to say so beyond the summary table. ci/publish-package.ps1 pushes the tag '/' on the published commit once each package is uploaded. The workflow now reads the tags on that commit (git ls-remote, as the repository is public) and pins each package the publish released to the version its tag names, waiting until PyPI's simple index, which pip reads, lists that version. It asks every $PyPIRetrySeconds (15) seconds and fails the run, naming the package and version, after $PyPIWaitSeconds (900) seconds. A package with no tag on that commit was not released by the publish, so it is pinned to its latest version as before, and a version given by hand is used as before. Run locally against PyPI with the step's script: a commit with no tags pinned every package to its latest version, a version given by hand was used for every package, and the 4.6.1 commit pinned the six pipeline packages to 4.6.1 at once and failed, with a short wait, on fiftyone-devicedetection-shared 4.6.1, which PyPI no longer lists. --- .github/workflows/examples-published.yml | 54 +++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml index 29ce434f..dc5660a5 100644 --- a/.github/workflows/examples-published.yml +++ b/.github/workflows/examples-published.yml @@ -4,7 +4,8 @@ name: Examples vs Published Packages # ci/packages.json marks for publishing is installed from PyPI, and only the # three examples packages and their tests come from this checkout. Each # package is pinned to the version given when the workflow is run by hand, -# or otherwise to its latest version on PyPI. +# after a publish to the version the publish released it at, and otherwise +# to its latest version on PyPI. # # It runs by hand on a branch (gh workflow run "Examples vs Published # Packages" --ref ), after each run of the two workflows that @@ -148,20 +149,71 @@ jobs: # Each package is pinned, so pip installs that version or fails, and # never an older one that happens to satisfy the others. + # + # After a publish, each package it released has the tag + # '/' on the commit it published, which + # ci/publish-package.ps1 pushes once the package is uploaded. PyPI can + # take a while to list a new version, so such a package is pinned to + # the version its tag names, waiting until PyPI lists it, rather than + # to whatever PyPI gives as the latest at that moment. Any other + # package is pinned to its latest version on PyPI. - name: Choose the published versions if: steps.keys.outputs.run == 'true' env: _51DEGREES_PACKAGE_VERSION: ${{ inputs.version }} + _51DEGREES_PUBLISHED_COMMIT: ${{ github.event.workflow_run.head_sha }} run: | + # The longest to wait for PyPI to list a version a publish tagged, + # and how long to wait between asking, in seconds. + $PyPIWaitSeconds = 900 + $PyPIRetrySeconds = 15 $version = "$env:_51DEGREES_PACKAGE_VERSION".Trim() if ($version -and $version -notmatch '^\d+\.\d+\.\d+$') { Write-Host "::error::'$version' is not a version such as 4.6.2." exit 1 } + # The version of each package the publish released, by the name + # PyPI gives it, read from the tags on the published commit. + $tagged = @{} + $commit = "$env:_51DEGREES_PUBLISHED_COMMIT".Trim() + if (-not $version -and $commit) { + $PSNativeCommandUseErrorActionPreference = $true + foreach ($line in (git ls-remote --tags origin)) { + $sha, $ref = $line -split "`t", 2 + $tag = $ref -replace '^refs/tags/' -replace '\^\{\}$' + if ($sha -eq $commit -and + $tag -match '^(?\w+)/(?\d+\.\d+\.\d+)$') { + $tagged[$Matches.name -replace '_', '-'] = $Matches.version + } + } + } + # Whether PyPI's simple index, which pip reads, lists a version. + function Test-OnPyPI([string]$Name, [string]$Version) { + try { + $index = Invoke-RestMethod "https://pypi.org/simple/$Name/" ` + -Headers @{ Accept = 'application/vnd.pypi.simple.v1+json' } + return @($index.versions) -contains $Version + } catch { + return $false + } + } $names = Get-Content -Raw ci/packages.json | ConvertFrom-Json | Where-Object Publish | ForEach-Object { $_.Name -replace '_', '-' } $pins = foreach ($name in $names) { $pinned = $version + if (-not $pinned -and $tagged.ContainsKey($name)) { + $pinned = $tagged[$name] + $deadline = (Get-Date).AddSeconds($PyPIWaitSeconds) + while (-not (Test-OnPyPI $name $pinned)) { + if ((Get-Date) -ge $deadline) { + Write-Host ("::error title=Not on PyPI::The publish " + + "tagged $name $pinned, which PyPI did not list " + + "within $PyPIWaitSeconds seconds.") + exit 1 + } + Start-Sleep -Seconds $PyPIRetrySeconds + } + } if (-not $pinned) { $pinned = (Invoke-RestMethod "https://pypi.org/pypi/$name/json").info.version } From 155cc986d362a031eccf60a27d230c5dd5ea52fc Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:28:40 +0000 Subject: [PATCH 7/7] Ignore a cache given to a cloud engine, with one warning, rather than raise CloudEngine.set_cache raised an exception, so code that gave a cloud engine a cache, which worked before, would stop at start-up after a patch release. A cloud engine accepts no evidence, so there is no key to use in a cache of its own, and the cache belongs on the Cloud Request Engine, where the pipeline builders now put it. set_cache on a CloudEngine, and so on DerivedCloud and every engine built on CloudEngine, now accepts the call and keeps no cache. It logs one warning for each engine, however often the engine is given a cache, naming the engine by its class and data key and saying to add the cache to the Cloud Request Engine. The warning goes to the logger of each pipeline the engine is in, or to the module's own logger (fiftyone_pipeline_cloudrequestengine.cloudengine) while it is in none, and nothing is logged as requests are processed. CloudEngine.process still never uses a cache. This is how the Rust cloud engines treat a cache setting, which is read and has no effect, with a warning logged. Tests, the first three failing while set_cache raised: - test_cloudengine_cache.py: a cache given before the engine is in a pipeline is accepted with one warning on the module's logger, and one given once the engine is in a pipeline with one warning on the pipeline's logger. In both, the engine keeps no cache, three requests each get their own value, the cache is never read or written and nothing more is logged. A cache assigned to the engine directly is never read or written either. - test_human_confidence.py: DerivedCloud accepts a cache with one warning naming it, and a cache given through set_cache or assigned directly never serves a redeemed result and is never read or written. Each warning test fails if the warning is logged on every call. --- .../cloudengine.py | 46 +++++-- .../humanconfidence.py | 8 +- .../tests/test_cloudengine_cache.py | 120 +++++++++++++++--- .../tests/test_human_confidence.py | 75 ++++++++--- 4 files changed, 198 insertions(+), 51 deletions(-) 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 258b30bd..7a4579a6 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py @@ -32,10 +32,14 @@ from .constants import Constants import json +import logging import threading from fiftyone_pipeline_engines.missingproperty_service import MissingPropertyService +# The logger a cloud engine warns through while no pipeline has given it one. +_LOGGER = logging.getLogger(__name__) + # Why a pipeline with a second CloudRequestEngine is refused. _ANOTHER_REQUEST_ENGINE = ( "This cloud engine is already in a pipeline with another Cloud Request " @@ -46,11 +50,13 @@ # 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.") +# Logged once for each cloud engine given a cache, with the engine's class +# name and data key. +CACHE_IGNORED = ( + "The cloud engine {} ('{}') was given a cache, which it ignores. 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): @@ -83,6 +89,9 @@ def __init__(self): self._properties_final = False self._properties_lock = threading.Lock() + # Whether set_cache has logged that this engine ignores a cache. + self._cache_ignored_logged = False + def get_evidence_key_filter(self): """! @@ -95,14 +104,29 @@ def get_evidence_key_filter(self): 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. + Accepted and ignored, so code that gives a cloud engine a cache + still runs. 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. + + The engine keeps no cache, and logs a warning that says so once, + however often it is given one. The warning goes to the logger of + each pipeline the engine is in, or to this module's logger while it + is in none. + + @type cache: DataKeyedCache + @param cache: the cache, which is never read or written """ - raise Exception(CACHE_ON_REQUEST_ENGINE) + if getattr(self, "_cache_ignored_logged", False): + return + self._cache_ignored_logged = True + message = CACHE_IGNORED.format(type(self).__name__, self.datakey) + if getattr(self, "pipelines", None): + self._log("warning", message) + else: + _LOGGER.warning(message) def process(self, flowdata): 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 bef83757..595999bc 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -339,10 +339,10 @@ class DerivedCloud(CloudEngine): 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. + Like every cloud engine, it ignores a cache it is given, with a + warning, 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 index 3c2f24b9..8589d326 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py @@ -22,8 +22,10 @@ """ 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. +its own. It accepts a cache it is given, so code that gives it one still +runs, keeps none and logs one warning saying so, and reads the response of +each request whatever it holds. The cache goes on the Cloud Request Engine +instead. """ import json @@ -34,12 +36,43 @@ BasicListEvidenceKeyFilter from fiftyone_pipeline_core.elementdata_dictionary import ElementDataDictionary from fiftyone_pipeline_core.flowelement import FlowElement +from fiftyone_pipeline_core.logger import Logger from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_engines.basic_dictionary_cache import \ BasicDictionaryCache USER_AGENT = "header.user-agent" +# The logger a cloud engine warns through while it is in no pipeline. +MODULE_LOGGER = "fiftyone_pipeline_cloudrequestengine.cloudengine" + + +class RecordingCache(BasicDictionaryCache): + """Records every read and write made of it.""" + + def __init__(self): + super(RecordingCache, self).__init__() + self.calls = [] + + def get_cache_value(self, key): + self.calls.append(("get", key)) + return super(RecordingCache, self).get_cache_value(key) + + def set_cache_value(self, key, value): + self.calls.append(("set", key)) + super(RecordingCache, self).set_cache_value(key, value) + + +class RecordingLogger(Logger): + """Keeps every entry the pipeline logs, as level and message.""" + + def __init__(self): + super(RecordingLogger, self).__init__("debug") + self.logged = [] + + def log_internal(self, level, log): + self.logged.append((level, log["message"])) + class StandInRequestEngine(FlowElement): """Stands in for a Cloud Request Engine, answering each request with the @@ -68,30 +101,83 @@ def device_engine(): 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({ + def pipeline_with(self, engine, logger=None): + builder = PipelineBuilder({ "add_javascript_builder": False, - "use_setheader_properties": False}) \ - .add(StandInRequestEngine()).add(engine).build() + "use_setheader_properties": False}) + if logger is not None: + builder.add_logger(logger) + pipeline = builder.add(StandInRequestEngine()).add(engine).build() self.addCleanup(pipeline.close) + return pipeline + @staticmethod + def values_of(pipeline, user_agents=("first", "second", "first")): values = [] - for user_agent in ("first", "second"): + for user_agent in user_agents: data = pipeline.create_flowdata() data.evidence.add(USER_AGENT, user_agent) data.process() values.append(data.device.value.value()) + return values + + def assert_names_the_engine(self, message): + self.assertIn("CloudEngine ('device')", message) + self.assertIn("Cloud Request Engine", message) + + def test_a_cache_given_before_a_pipeline_is_ignored_with_one_warning(self): + engine = self.device_engine() + cache = RecordingCache() + + with self.assertLogs(MODULE_LOGGER, "WARNING") as logged: + engine.set_cache(cache) + engine.set_cache(cache) + self.assertEqual(1, len(logged.records)) + self.assert_names_the_engine(logged.records[0].getMessage()) + self.assertFalse(hasattr(engine, "cache")) + + logger = RecordingLogger() + pipeline = self.pipeline_with(engine, logger) + with self.assertNoLogs(MODULE_LOGGER, "WARNING"): + self.assertEqual( + ["first", "second", "first"], self.values_of(pipeline)) + self.assertEqual([], cache.calls) + self.assertEqual( + [], [entry for entry in logger.logged + if "given a cache" in entry[1]]) + + def test_a_cache_given_in_a_pipeline_is_ignored_with_one_warning(self): + """The warning goes to the pipeline's logger, once, and is not + logged again as requests are processed.""" + + engine = self.device_engine() + logger = RecordingLogger() + pipeline = self.pipeline_with(engine, logger) + cache = RecordingCache() + + with self.assertNoLogs(MODULE_LOGGER, "WARNING"): + engine.set_cache(cache) + engine.set_cache(RecordingCache()) + values = self.values_of(pipeline) + + warned = [message for level, message in logger.logged + if "given a cache" in message] + self.assertEqual(1, len(warned), logger.logged) + self.assert_names_the_engine(warned[0]) + self.assertIn(("warning", warned[0]), logger.logged) + self.assertEqual(["first", "second", "first"], values) + self.assertEqual([], cache.calls) + self.assertFalse(hasattr(engine, "cache")) + + def test_a_cloud_engine_reads_each_response_whatever_it_holds(self): + engine = self.device_engine() + # A cache assigned to the engine directly, bypassing set_cache. + engine.cache = RecordingCache() + pipeline = self.pipeline_with(engine) - self.assertEqual(["first", "second"], values) - self.assertEqual({}, engine.cache.cache) + self.assertEqual( + ["first", "second", "first"], self.values_of(pipeline)) + self.assertEqual([], engine.cache.calls) if __name__ == "__main__": diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py index 9c3d412b..67985c11 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py @@ -76,6 +76,9 @@ "No value: the remote server returned a HumanConfidenceSource this " "package does not know. Update the package.") +# The logger a cloud engine warns through while it is in no pipeline. +CLOUD_ENGINE_LOGGER = "fiftyone_pipeline_cloudrequestengine.cloudengine" + # A null reason as the cloud service gives it for a sealed result it did # not redeem, recorded here as an answer. EXPIRED_REASON = ( @@ -94,6 +97,22 @@ def reply(body, status=200): return response +class RecordingCache(BasicDictionaryCache): + """Records every read and write made of it.""" + + def __init__(self): + super(RecordingCache, self).__init__() + self.calls = [] + + def get_cache_value(self, key): + self.calls.append(("get", key)) + return super(RecordingCache, self).get_cache_value(key) + + def set_cache_value(self, key, value): + self.calls.append(("set", key)) + super(RecordingCache, self).set_cache_value(key, value) + + class StandIn(object): """Answers discovery for a key carrying the two properties, and each data request with the answer set, keeping the data requests made.""" @@ -422,27 +441,45 @@ 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): + def test_derived_cloud_ignores_a_cache_with_one_warning(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") + with self.assertLogs(CLOUD_ENGINE_LOGGER, "WARNING") as logged: + derived.set_cache(BasicDictionaryCache()) + derived.set_cache(BasicDictionaryCache()) + self.assertEqual(1, len(logged.records)) + message = logged.records[0].getMessage() + self.assertIn("DerivedCloud ('derived')", message) + self.assertIn("Cloud Request Engine", message) + self.assertFalse(hasattr(derived, "cache")) + + def test_a_cache_given_to_derived_cloud_never_serves_a_redeemed_result( + self): + for given in ("set_cache", "assigned"): + with self.subTest(given=given): + self.cloud.data_requests.clear() + derived = DerivedCloud() + cache = RecordingCache() + if given == "set_cache": + with self.assertLogs(CLOUD_ENGINE_LOGGER, "WARNING"): + derived.set_cache(cache) + else: + # A cache assigned directly, bypassing set_cache. + derived.cache = cache + 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) + 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([], cache.calls) def test_a_request_with_a_sealed_result_skips_the_cache(self): cache = BasicDictionaryCache()