From 1664eafe809aa5420cf744e7a3c487ecec0792d0 Mon Sep 17 00:00:00 2001 From: James Rogers Date: Thu, 26 Nov 2026 12:50:50 +0000 Subject: [PATCH 01/24] Test that the server route passes the session id, sequence, browser test answers and visitor connection to the cloud --- .../tests/test_server_route_pass_through.py | 199 ++++++++++++++++++ 1 file changed, 199 insertions(+) create mode 100644 pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py 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 new file mode 100644 index 00000000..1ab9e86a --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py @@ -0,0 +1,199 @@ +# ********************************************************************* +# 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 server route. A publisher's server serves the pipeline's JavaScript +to the browser, and the browser posts the answers of the scripts it ran +back to the server, which passes them on to the cloud through the Cloud +Request Engine. These tests follow that back and forth through a Flask +application, as a web integration serves it, and check what reaches the +cloud on each iteration: the session id, the sequence, the browser test +answers, and the visitor's IP address, JA4 and H2 that the server supplies +as query evidence.""" + +import re +import unittest +import warnings +from unittest import mock + +from flask import Flask, request + +from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import \ + CloudRequestEngine +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder +from fiftyone_pipeline_core import web +from fiftyone_pipeline_core.web import javascript_response, json_response + +from .classes.mockrequestclient import MockRequestClient + +CHROME = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36") + +# The visitor's connection as the server's TLS terminator saw it. The JA4 +# is in the form the cloud captures. The H2 is the HTTP/2 SETTINGS text. +VISITOR_IP = "203.0.113.24" +VISITOR_JA4 = "t13d1516h2_8daaf6152771_02713d6af862" +VISITOR_H2 = "1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p" + +# 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. +ANSWER_NAME = "51D_k3Jq9xT" +ANSWER_VALUE = "3z|" + "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" + +SESSION_ID = re.compile(r'var sessionId = "([^"]*)";') +SEQUENCE = re.compile(r"var sequence = ([0-9]+);") + + +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 + server adds the visitor's IP address, JA4 and H2 as query evidence, as + a server behind a TLS terminator does.""" + + pipeline = PipelineBuilder({ + "javascript_builder_settings": { + "endpoint": "/json", "minify": False}, + }).add(engine).build() + + app = Flask(__name__) + + def evidence_of(req): + evidence = original(req) + if supply_connection: + evidence["query.client-ip"] = VISITOR_IP + evidence["query.ja4"] = VISITOR_JA4 + evidence["query.h2"] = VISITOR_H2 + return evidence + + # The web integration reads the request through webevidence, so the + # server's own values are added by wrapping it while a request is + # answered. + original = web.webevidence + + @app.route("/51Degrees.core.js") + def javascript(): + with mock.patch.object(web, "webevidence", evidence_of): + return javascript_response(pipeline, request) + + @app.route("/json", methods=["POST"]) + def results(): + with mock.patch.object(web, "webevidence", evidence_of): + return json_response(pipeline, request) + + return app.test_client() + + +class ServerRoutePassThroughTests(unittest.TestCase): + + def setUp(self): + self.http = MockRequestClient() + self.engine = CloudRequestEngine({ + "resource_key": "resource_key", + "http_client": self.http, + }) + + def data_requests(self): + """The body of every data request the engine made, in order.""" + return [content for (_, url, content) in self.http.requests + if "resource_key.json" in url] + + def script_values(self, response): + """The session id and the sequence the script was written with.""" + text = response.get_data(as_text=True) + return (SESSION_ID.search(text).group(1), + int(SEQUENCE.search(text).group(1))) + + def run_iterations(self, client): + """The browser's side of the back and forth. It loads the script, + then posts the session id and the sequence the script holds with + its answers, twice, as a page does when a snippet's answers lead + to another iteration.""" + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + first = client.get("/51Degrees.core.js", + headers={"User-Agent": CHROME}) + self.assertEqual(200, first.status_code) + session_id, sequence = self.script_values(first) + client.set_cookie(COOKIE_NAME, COOKIE_VALUE) + for _ in range(2): + response = client.post("/json", headers={ + "User-Agent": CHROME, + }, data={ + "session-id": session_id, + "sequence": str(sequence), + ANSWER_NAME: ANSWER_VALUE, + }) + self.assertEqual(200, response.status_code) + sequence += 1 + return session_id + + 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.""" + + session_id = self.run_iterations(make_app(self.engine, False)) + bodies = self.data_requests() + self.assertEqual(3, len(bodies)) + + sequences = [int(body["sequence"]) for body in bodies] + self.assertEqual( + [sequences[0], sequences[0] + 1, sequences[0] + 2], sequences) + for body in bodies: + self.assertEqual(session_id, body["session-id"]) + self.assertEqual(CHROME, body["user-agent"]) + for body in bodies[1:]: + self.assertEqual(ANSWER_VALUE, body[ANSWER_NAME]) + self.assertEqual(COOKIE_VALUE, body[COOKIE_NAME]) + self.assertNotIn(ANSWER_NAME, bodies[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 + names it reads, with the supplied address replacing the address + the request arrived from.""" + + self.run_iterations(make_app(self.engine, True)) + bodies = self.data_requests() + self.assertEqual(3, len(bodies)) + for body in bodies: + self.assertEqual(VISITOR_IP, body["client-ip"]) + self.assertEqual(VISITOR_JA4, body["ja4"]) + self.assertEqual(VISITOR_H2, body["h2"]) + + def test_without_supplied_values_the_connection_is_the_requests(self): + """With nothing supplied, the address sent is the one the request + arrived from, and no JA4 or H2 is sent.""" + + self.run_iterations(make_app(self.engine, False)) + for body in self.data_requests(): + self.assertEqual("127.0.0.1", body["client-ip"]) + self.assertNotIn("ja4", body) + self.assertNotIn("h2", body) + + +if __name__ == "__main__": + unittest.main() From 5f1996e26662de09355e77e92055c3e2b3a1741a Mon Sep 17 00:00:00 2001 From: James Rogers Date: Thu, 26 Nov 2026 13:47:37 +0000 Subject: [PATCH 02/24] Install Flask for the cloud request engine tests --- pipeline/fiftyone_pipeline_cloudrequestengine/tox.ini | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tox.ini b/pipeline/fiftyone_pipeline_cloudrequestengine/tox.ini index 69bf8f95..7c3cbc92 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tox.ini +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tox.ini @@ -6,6 +6,9 @@ deps = pytest>=6 pytest-cov parameterized + # The server route tests serve the JavaScript through a Flask + # application, as a web integration does. + flask [testenv] description = run the tests with pytest From 188da3355e2a9253fce51be40856403ecb589871 Mon Sep 17 00:00:00 2001 From: James Rogers Date: Thu, 26 Nov 2026 14:01:38 +0000 Subject: [PATCH 03/24] Send every page iteration and supplied connection to the cloud when a cache is set --- .../cloudrequestengine.py | 40 +++++++++++++- .../constants.py | 6 +++ .../tests/test_server_route_pass_through.py | 54 +++++++++++++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) 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 f62223cf..8deac5d7 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py @@ -785,7 +785,12 @@ def process(self, flowdata): @param flowdata: the FlowData to process """ - result = super(CloudRequestEngine, self).process(flowdata) + if hasattr(self, "cache") and self.bypasses_cache(flowdata.evidence): + # Neither served from the cache nor stored in it. See + # bypasses_cache. + result = self.process_internal(flowdata) + else: + result = super(CloudRequestEngine, self).process(flowdata) # FlowData keeps each element's data under its datakey in lower case. data = flowdata.data.get(self.datakey.lower()) @@ -794,6 +799,39 @@ def process(self, flowdata): return result + @staticmethod + def bypasses_cache(evidence): + + """! + Whether a request goes to the cloud service whatever the cache + holds, and its answer is not stored. The cache key is made from the + evidence keys the service lists, but the engine sends every evidence + value. A page iteration carries the session id and the sequence, + and a server may supply the visitor's JA4 and H2, none of which the + service lists. 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 the service waits for before it makes a 51Did, 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. + + @type evidence: Evidence + @param evidence: The flow data's Evidence + + @rtype: bool + @return: True if the request bypasses the cache + """ + + unaccepted = getattr(evidence, "get_unaccepted", dict)() + for source in (unaccepted, evidence.get_all()): + for key in source: + name = str(key).partition(Constants.EVIDENCE_SEPERATOR) + name = (name[2] if name[1] else name[0]).lower() + if name in Constants.UNCACHED_EVIDENCE_NAMES: + return True + return False + def is_cacheable(self, data): """! 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 439741e4..c01a43c1 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py @@ -137,6 +137,12 @@ class Constants: RESOURCE_PARAMETER, LICENSE_PARAMETER, LICENCE_SPELLING, VALUES_PARAMETER) + # Evidence names, under any prefix, that the service reads but does not + # list, so the cache key leaves them out. A request carrying one goes + # to the service whatever the cache holds. See + # CloudRequestEngine.bypasses_cache. + UNCACHED_EVIDENCE_NAMES = ("session-id", "sequence", "ja4", "h2") + # The path, below the base URL, of the data endpoint that takes no # resource key in its route, used when the engine authenticates on a # licence key alone. 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 1ab9e86a..3ffe375e 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 @@ -41,6 +41,8 @@ from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder from fiftyone_pipeline_core import web from fiftyone_pipeline_core.web import javascript_response, json_response +from fiftyone_pipeline_engines.basic_dictionary_cache import ( + BasicDictionaryCache) from .classes.mockrequestclient import MockRequestClient @@ -184,6 +186,58 @@ def test_the_server_supplies_the_visitors_connection(self): self.assertEqual(VISITOR_JA4, body["ja4"]) self.assertEqual(VISITOR_H2, body["h2"]) + def test_every_iteration_reaches_the_cloud_through_a_cache(self): + """The cache key is made from the evidence keys the cloud lists, + and the cloud lists none of the session id, the sequence, the + answers, the JA4 or the H2. So two iterations of one page share a + key, and without care the iteration carrying the answers would be + answered from the cache and never reach the cloud.""" + + self.engine.set_cache(BasicDictionaryCache()) + session_id = self.run_iterations(make_app(self.engine, True)) + bodies = self.data_requests() + self.assertEqual(3, len(bodies)) + for body in bodies: + self.assertEqual(session_id, body["session-id"]) + self.assertEqual(VISITOR_JA4, body["ja4"]) + for body in bodies[1:]: + self.assertEqual(ANSWER_VALUE, body[ANSWER_NAME]) + + def test_a_supplied_connection_is_never_served_from_a_cache(self): + """A server call with no page iteration, but with the visitor's + JA4 and H2, goes to the cloud each time, because the cloud judges + the call on them and the cache key leaves them out.""" + + self.engine.set_cache(BasicDictionaryCache()) + pipeline = PipelineBuilder({"add_javascript_builder": False}) \ + .add(self.engine).build() + for ja4 in (VISITOR_JA4, "t13d1517h2_8daaf6152771_b1ff8ab2d16f"): + data = pipeline.create_flowdata() + data.evidence.add("header.user-agent", CHROME) + data.evidence.add("query.ja4", ja4) + data.evidence.add("query.h2", VISITOR_H2) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + data.process() + self.assertEqual( + [VISITOR_JA4, "t13d1517h2_8daaf6152771_b1ff8ab2d16f"], + [body["ja4"] for body in self.data_requests()]) + + def test_any_other_call_is_still_served_from_a_cache(self): + """A call that is neither a page iteration nor carries a supplied + connection is cached as before.""" + + self.engine.set_cache(BasicDictionaryCache()) + pipeline = PipelineBuilder({"add_javascript_builder": False}) \ + .add(self.engine).build() + for _ in range(2): + data = pipeline.create_flowdata() + data.evidence.add("query.User-Agent", CHROME) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + data.process() + self.assertEqual(1, len(self.data_requests())) + def test_without_supplied_values_the_connection_is_the_requests(self): """With nothing supplied, the address sent is the one the request arrived from, and no JA4 or H2 is sent.""" From a022acd6a1c43040525cee2bfb6a054cd48729ec Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 07:50:28 +0000 Subject: [PATCH 04/24] Test the examples against the packages published on PyPI Nothing in CI ran the examples against the packages customers install from PyPI, so a release whose packages do not work together, or that leaves out something the examples need, was only found by a customer. The new workflow, Examples vs Published Packages, installs every package ci/packages.json marks for publishing from PyPI, each pinned to the version given when the workflow is run by hand or otherwise to its latest version, and takes only the three examples packages and their tests from this checkout. It checks that each published package was installed from PyPI at the pinned version, then runs the tests of the Device Detection, IP Intelligence and Pipeline examples on the free data files, with the resource key and licence keys the cloud tests read. A missing key, a missing data file or a skipped test fails the run, because a run that skips has checked nothing. The tests marked staging are left out, as only the Cloud Human Confidence workflow is given the staging cloud. It runs by hand, after each run of Publish or Nightly Pipeline that was not cancelled, and on a pull request that changes the workflow. Checked with ci/check-environment-variable-names.ps1 and the Pester tests in ci/key-names.Tests.ps1, ci/check-environment-variable-names.Tests.ps1 and ci/free-threaded-python.Tests.ps1, 246 passed and none failed. --- .github/workflows/examples-published.yml | 295 +++++++++++++++++++++++ 1 file changed, 295 insertions(+) create mode 100644 .github/workflows/examples-published.yml diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml new file mode 100644 index 00000000..3dcf518f --- /dev/null +++ b/.github/workflows/examples-published.yml @@ -0,0 +1,295 @@ +name: Examples vs Published Packages + +# Runs the examples' own tests against the packages on PyPI. Every package +# 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. +# +# It runs by hand on a branch (gh workflow run "Examples vs Published +# Packages" --ref ), after each run of the two workflows that +# publish, and on a pull request that changes this file. An example that +# needs a change not yet released fails here until the release, which is why +# it does not run on other pull requests. +# +# The tests run on the free data files and with the keys the cloud tests +# need. A missing key or data file fails the run, and so does a test that +# skipped, because a run that skips has checked nothing. + +on: + workflow_dispatch: + inputs: + version: + description: 'Version of every published package, such as 4.6.2, or empty for the latest of each on PyPI' + type: string + default: '' + # A run of either may publish packages, and one that failed may still have + # published some, so only a cancelled run is passed over. + workflow_run: + workflows: [Publish, Nightly Pipeline] + types: [completed] + pull_request: + paths: + - '.github/workflows/examples-published.yml' + +permissions: + contents: read + +defaults: + run: + shell: pwsh + +jobs: + published: + name: examples vs published packages + if: >- + github.event_name != 'workflow_run' || + github.event.workflow_run.conclusion != 'cancelled' + runs-on: ubuntu-latest + timeout-minutes: 60 + steps: + # A pull request from a fork gets no secrets, so it is skipped with a + # warning. Anywhere else a missing key is an error. Only the Pipeline + # examples' tests read _51DEGREES_LICENSE_KEY, for a licence key to + # look for in the page the Human Confidence example serves. + - name: Check the keys are available + id: keys + env: + _51DEGREES_RESOURCE_KEY_BESPOKE: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} + _51DEGREES_LICENSE_KEY_BESPOKE: ${{ secrets._51DEGREES_LICENSE_KEY_BESPOKE }} + _51DEGREES_LICENSE_KEY: ${{ secrets._51DEGREES_LICENSE_KEY }} + _51DEGREES_FROM_FORK: ${{ github.event.pull_request.head.repo.fork == true }} + run: | + $names = '_51DEGREES_RESOURCE_KEY_BESPOKE', + '_51DEGREES_LICENSE_KEY_BESPOKE', '_51DEGREES_LICENSE_KEY' + $missing = @($names | + Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) + if (-not $missing) { + 'run=true' >> $env:GITHUB_OUTPUT + exit 0 + } + $list = $missing -join ', ' + if ($env:_51DEGREES_FROM_FORK -eq 'true') { + Write-Host ("::warning title=No keys::A fork has no $list, so " + + "the examples are not tested against the published packages.") + 'run=false' >> $env:GITHUB_OUTPUT + exit 0 + } + Write-Host ("::error title=Missing organization secrets::$list " + + "not available to this workflow.") + exit 1 + + # After a publish, the commit that was published. The data repository + # inside cxx holds the evidence and the comparison files the IP + # Intelligence tests read, and a link for each data file. + - name: Checkout repository + if: steps.keys.outputs.run == 'true' + uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha }} + persist-credentials: false + submodules: recursive + + - name: Set up Python + if: steps.keys.outputs.run == 'true' + uses: actions/setup-python@v5 + with: + python-version: '3.14' + + # The free data files, from the assets common-ci fetches and keeps in + # the Actions cache for the day, so nothing follows the links here. + - name: Fetch the free data files + if: steps.keys.outputs.run == 'true' + uses: 51Degrees/common-ci/actions/fetch-assets@main + with: + cache: 'true' + assets: | + 51Degrees-LiteV4.1.hash + 20000 Evidence Records.yml + 51Degrees-IPIV4AsnIpiV41.ipi + 51Degrees-LiteIpiV41.ipi + + # Under the names the data repository saves them as, where the + # examples look. A missing file fails the job here, because the tests + # would skip without it. + - name: Put the free data files where the examples look for them + if: steps.keys.outputs.run == 'true' + run: | + $dd = 'cxx/data/device-detection' + $ipi = 'cxx/data/ip-intelligence' + $files = [ordered]@{ + '51Degrees-LiteV4.1.hash' = "$dd/51Degrees-LiteV4.1.hash" + '20000 Evidence Records.yml' = "$dd/20000 Evidence Records.yml" + '51Degrees-IPIV4AsnIpiV41.ipi' = "$ipi/51Degrees-IPIV4AsnIpiV41.ipi" + '51Degrees-LiteIpiV41.ipi' = "$ipi/51Degrees-LiteV41.ipi" + } + foreach ($asset in $files.Keys) { + $source = Join-Path assets $asset + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { + Write-Host "::error title=Missing data file::$asset was not fetched." + exit 1 + } + Copy-Item -LiteralPath $source -Destination $files[$asset] + } + + # Each package is pinned, so pip installs that version or fails, and + # never an older one that happens to satisfy the others. + - name: Choose the published versions + if: steps.keys.outputs.run == 'true' + env: + _51DEGREES_PACKAGE_VERSION: ${{ inputs.version }} + run: | + $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 + } + $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) { + $pinned = (Invoke-RestMethod "https://pypi.org/pypi/$name/json").info.version + } + "$name==$pinned" + } + $pins | Set-Content '${{ runner.temp }}/published.txt' + @('| Package | Version |', '| --- | --- |') + + ($pins | ForEach-Object { "| $($_ -replace '==', ' | ') |" }) | + Add-Content $env:GITHUB_STEP_SUMMARY + $pins + + # The examples' dependencies on the published packages are held to the + # pinned versions, and everything else they need comes from PyPI. The + # two on-premise packages are source distributions, which pip compiles + # as it does on a customer's machine. + - name: Install the published packages and the examples + if: steps.keys.outputs.run == 'true' + run: | + $PSNativeCommandUseErrorActionPreference = $true + $published = '${{ runner.temp }}/published.txt' + python -m pip install --upgrade pip + python -m pip install -r $published + python -m pip install -c $published pytest ` + ./device-detection/fiftyone_devicedetection_examples ` + './ip-intelligence/fiftyone_ipintelligence_examples[mixed]' ` + './pipeline/fiftyone_pipeline_cloudrequestengine/examples[test]' + python -m pip check + + # A package installed from a folder or a URL records it in + # direct_url.json, and one from PyPI does not. + - name: Check each published package came from PyPI + if: steps.keys.outputs.run == 'true' + shell: python + run: | + import importlib + import importlib.metadata as metadata + import pathlib + import sys + import sysconfig + + site = {pathlib.Path(sysconfig.get_paths()[key]).resolve() + for key in ("purelib", "platlib")} + pins = pathlib.Path( + r"${{ runner.temp }}/published.txt").read_text().split() + problems = [] + for pin in pins: + name, version = pin.split("==") + distribution = metadata.distribution(name) + module = importlib.import_module(name.replace("-", "_")) + path = pathlib.Path(module.__file__).resolve() + print(f"{name} {distribution.version} {path}") + if distribution.version != version: + problems.append( + f"{name} is {distribution.version}, not {version}.") + if distribution.read_text("direct_url.json") is not None: + problems.append(f"{name} was not installed from PyPI.") + if not any(folder in path.parents for folder in site): + problems.append(f"{name} was imported from {path}.") + for problem in problems: + print(f"::error::{problem}") + sys.exit(1 if problems else 0) + + # Each package's tests run from its folder, as its tox.ini runs them, + # and the Device Detection ones without _51DEGREES_LICENSE_KEY, which + # that tox.ini empties. The tests marked staging call the staging + # cloud, which only the Cloud Human Confidence workflow is given, so + # they are left out. Every package is run even after one fails. + - name: Test the examples against the published packages + if: steps.keys.outputs.run == 'true' + env: + _51DEGREES_RESOURCE_KEY_BESPOKE: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} + _51DEGREES_LICENSE_KEY_BESPOKE: ${{ secrets._51DEGREES_LICENSE_KEY_BESPOKE }} + _51DEGREES_LICENSE_KEY: ${{ secrets._51DEGREES_LICENSE_KEY }} + # The cloud service the tests ask. The name is removed when the + # variable is not set, so the tests ask the public one. + _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + run: | + if (-not $env:_51DEGREES_CLOUD_ENDPOINT) { + Remove-Item Env:_51DEGREES_CLOUD_ENDPOINT -ErrorAction SilentlyContinue + } + $licenseKey = $env:_51DEGREES_LICENSE_KEY + $env:_51DEGREES_DD_PATH = (Resolve-Path 'cxx/data/device-detection/51Degrees-LiteV4.1.hash').Path + $env:_51DEGREES_IPI_PATH = (Resolve-Path 'cxx/data/ip-intelligence/51Degrees-LiteV41.ipi').Path + $runs = @( + @{ Name = 'fiftyone_devicedetection_examples' + Path = 'device-detection/fiftyone_devicedetection_examples' + LicenseKey = $false; Arguments = @() } + @{ Name = 'fiftyone_ipintelligence_examples' + Path = 'ip-intelligence/fiftyone_ipintelligence_examples' + LicenseKey = $false; Arguments = @() } + @{ Name = 'fiftyone_pipeline_examples' + Path = 'pipeline/fiftyone_pipeline_cloudrequestengine/examples' + LicenseKey = $true; Arguments = @('-m', 'not staging') } + ) + $results = New-Item -ItemType Directory -Force -Path '${{ runner.temp }}/results' + $summary = @( + '| Examples | Tests | Passed | Failed | Errors | Skipped |' + '| --- | --- | --- | --- | --- | --- |') + $failed = $false + foreach ($run in $runs) { + if ($run.LicenseKey) { + $env:_51DEGREES_LICENSE_KEY = $licenseKey + } else { + Remove-Item Env:_51DEGREES_LICENSE_KEY -ErrorAction SilentlyContinue + } + $report = Join-Path $results "$($run.Name).xml" + Write-Host "::group::$($run.Name)" + Push-Location $run.Path + python -m pytest -p no:cacheprovider -rs "--junit-xml=$report" @($run.Arguments) + $code = $LASTEXITCODE + Pop-Location + Write-Host '::endgroup::' + if (-not (Test-Path $report)) { + Write-Host "::error title=$($run.Name)::pytest exited with code $code and wrote no results." + $summary += "| $($run.Name) | none | | | | |" + $failed = $true + continue + } + $suite = ([xml](Get-Content -Raw $report)).SelectSingleNode('//testsuite') + $tests = [int]$suite.tests + $failures = [int]$suite.failures + $errors = [int]$suite.errors + $skipped = [int]$suite.skipped + $passed = $tests - $failures - $errors - $skipped + $summary += "| $($run.Name) | $tests | $passed | $failures | $errors | $skipped |" + if ($code -ne 0) { + Write-Host "::error title=$($run.Name)::pytest exited with code $code." + $failed = $true + } + if ($tests -eq 0) { + Write-Host "::error title=$($run.Name)::No test ran." + $failed = $true + } + foreach ($case in $suite.SelectNodes('testcase[failure or error]')) { + Write-Host "::error title=$($run.Name)::$($case.classname).$($case.name) failed." + } + foreach ($case in $suite.SelectNodes('testcase[skipped]')) { + Write-Host ("::error title=$($run.Name)::$($case.classname)." + + "$($case.name) skipped, so it checked nothing. " + + "$($case.skipped.message)") + $failed = $true + } + } + $summary | Add-Content $env:GITHUB_STEP_SUMMARY + exit ($failed ? 1 : 0) From 8e261c6d07465be950ccd9cd7292cf9e20173d29 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 08:31:56 +0000 Subject: [PATCH 05/24] Give the examples' tests the TAC data file and run every test module The first run against the packages on PyPI (https://github.com/51Degrees/51degrees-python/actions/runs/46601762739, attempt 3) showed two gaps in the job. The Device Detection tests of the data file update example serve a copy of TAC-HashV41.hash, and failed with "TAC-HashV41.hash is missing". The job now fetches it with common-ci's fetch-assets action and the data license from LICENSE_KEY_V4TAC_IPIV4ENTERPRISE, without keeping it in the Actions cache because it is licensed, and puts it in cxx/data/device-detection. A test module that could not be imported stopped pytest before any test of that package ran, so the IP Intelligence and Pipeline examples gave no totals. pytest now runs with --continue-on-collection-errors, which still fails the job on each module that cannot be imported. Checked with ci/check-environment-variable-names.ps1 and the Pester tests in ci/key-names.Tests.ps1, ci/check-environment-variable-names.Tests.ps1 and ci/free-threaded-python.Tests.ps1, 246 passed and none failed. --- .github/workflows/examples-published.yml | 33 ++++++++++++++++++------ 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml index 3dcf518f..476f00a3 100644 --- a/.github/workflows/examples-published.yml +++ b/.github/workflows/examples-published.yml @@ -12,9 +12,10 @@ name: Examples vs Published Packages # needs a change not yet released fails here until the release, which is why # it does not run on other pull requests. # -# The tests run on the free data files and with the keys the cloud tests -# need. A missing key or data file fails the run, and so does a test that -# skipped, because a run that skips has checked nothing. +# The tests run on the free data files, with the TAC data file the data file +# update example's tests need and the keys the cloud tests need. A missing +# key or data file fails the run, and so does a test that skipped, because a +# run that skips has checked nothing. on: workflow_dispatch: @@ -109,10 +110,23 @@ jobs: 51Degrees-IPIV4AsnIpiV41.ipi 51Degrees-LiteIpiV41.ipi + # The Device Detection tests of the data file update example serve a + # copy of the TAC data file. It comes from the Distributor with the + # data license, which common-ci's fetch reads as + # _51DEGREES_LICENSE_KEY and fails without. The file is licensed, so + # it is not kept in the Actions cache. + - name: Fetch the TAC data file + if: steps.keys.outputs.run == 'true' + uses: 51Degrees/common-ci/actions/fetch-assets@main + env: + _51DEGREES_LICENSE_KEY: ${{ secrets.LICENSE_KEY_V4TAC_IPIV4ENTERPRISE }} + with: + assets: TAC-HashV41.hash + # Under the names the data repository saves them as, where the # examples look. A missing file fails the job here, because the tests - # would skip without it. - - name: Put the free data files where the examples look for them + # would skip or fail without it. + - name: Put the data files where the examples look for them if: steps.keys.outputs.run == 'true' run: | $dd = 'cxx/data/device-detection' @@ -120,6 +134,7 @@ jobs: $files = [ordered]@{ '51Degrees-LiteV4.1.hash' = "$dd/51Degrees-LiteV4.1.hash" '20000 Evidence Records.yml' = "$dd/20000 Evidence Records.yml" + 'TAC-HashV41.hash' = "$dd/TAC-HashV41.hash" '51Degrees-IPIV4AsnIpiV41.ipi' = "$ipi/51Degrees-IPIV4AsnIpiV41.ipi" '51Degrees-LiteIpiV41.ipi' = "$ipi/51Degrees-LiteV41.ipi" } @@ -129,7 +144,7 @@ jobs: Write-Host "::error title=Missing data file::$asset was not fetched." exit 1 } - Copy-Item -LiteralPath $source -Destination $files[$asset] + Move-Item -LiteralPath $source -Destination $files[$asset] } # Each package is pinned, so pip installs that version or fails, and @@ -214,7 +229,8 @@ jobs: # and the Device Detection ones without _51DEGREES_LICENSE_KEY, which # that tox.ini empties. The tests marked staging call the staging # cloud, which only the Cloud Human Confidence workflow is given, so - # they are left out. Every package is run even after one fails. + # they are left out. Every package is run even after one fails, and + # every test module even after one cannot be imported. - name: Test the examples against the published packages if: steps.keys.outputs.run == 'true' env: @@ -256,7 +272,8 @@ jobs: $report = Join-Path $results "$($run.Name).xml" Write-Host "::group::$($run.Name)" Push-Location $run.Path - python -m pytest -p no:cacheprovider -rs "--junit-xml=$report" @($run.Arguments) + python -m pytest -p no:cacheprovider -rs --continue-on-collection-errors ` + "--junit-xml=$report" @($run.Arguments) $code = $LASTEXITCODE Pop-Location Write-Host '::endgroup::' From 8c17f68992a52d458114f9741c35ede8d51f7e29 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Wed, 18 Nov 2026 02:58:57 +0000 Subject: [PATCH 06/24] Start Node once before the object name tests, outside their time limit Each call to Node in test_javascriptbuilder_object_name.py had a 60 second limit, and the first call on a runner also paid for Node's first start, which took up to 17.8 seconds on the Windows runners measured and once more than 60 seconds. The module now starts Node once before the tests, with a limit of 300 seconds for that start, so each check and run of the script keeps the 60 second limit for its own work. Both limits are named constants. What the tests check is unchanged. --- .../tests/test_javascriptbuilder_object_name.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 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 c6e2e400..b48b59d6 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py @@ -93,10 +93,23 @@ def _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=60) - + [NODE] + list(args), capture_output=True, text=True, + timeout=NODE_CALL_SECONDS) def _declared_names(script): return re.findall( From fc120d69f27f3a0f4481297ba5ec9b1195c96f8e Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 08:38:22 +0000 Subject: [PATCH 07/24] Keep two blank lines before _declared_names in the object name tests --- .../test_javascriptbuilder_object_name.py | 699 +++++++++--------- 1 file changed, 350 insertions(+), 349 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 b48b59d6..86ad3582 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py @@ -1,349 +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 d7ff3857b5068fc197f949da0b1e18db899d2564 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 08:51:52 +0000 Subject: [PATCH 08/24] Keep every cloud response made for one visitor out of the response cache A cloud response made for one visitor is never stored in or served from the response cache. The branch already kept out a response holding a 51Did (a top-level fodid) and a request carrying a session id, a sequence, a JA4 or an H2, and rc kept out a request carrying a sealed result to redeem. is_cacheable now also keeps out: - a response carrying a sealed Human Confidence result, being a derived.humanconfidence whose value is text that is not blank and is none of High, Medium or Low. HumanConfidenceSource is never read, because the route decides sealing and a sealed result can be Passive or Active. - a response carrying the browser tests' script, being a browserderived.browsertestsjavascript that is not blank. Member names are compared in any case, as fodid already was. The comments on bypasses_cache and UNCACHED_EVIDENCE_NAMES now give the reason the rule gives, a request made for one visitor, and no longer say the cloud service does not list the JA4 and H2, which its evidence key list now does. New tests in test_cloudrequestengine_cache.py cover a sealed Passive result, a sealed result with any source, an unsealed Active value (High, Medium and Low are cached), a null value, a blank value, the names in any case, the browser tests' script and a null or blank script. The cloud request engine's tests pass with no keys set (194 passed, 2 skipped live licence key tests, 4 live tests deselected), and taking out either new check fails four of the new tests. --- .../cloudrequestengine.py | 75 ++++++++++++---- .../constants.py | 17 +++- .../humanconfidence.py | 17 ++++ .../tests/test_cloudrequestengine_cache.py | 89 ++++++++++++++++++- .../tests/test_server_route_pass_through.py | 12 +-- 5 files changed, 181 insertions(+), 29 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 cefd65d2..3f2e71e1 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py @@ -66,6 +66,25 @@ def _endpoint_from_environment(): return os.environ.get(Constants.CLOUD_ENDPOINT) or None +def _properties(answer, data_key, name): + + """! + Every value a response gives for a property, being a member named name + within a top-level member named data_key, each name compared in any + case. A response may hold no such member, or more than one that + differs only in case. + + @type answer: dict + @param answer: the response's JSON, read as an object + """ + + for key, section in answer.items(): + if str(key).lower() == data_key and isinstance(section, dict): + for member, value in section.items(): + if str(member).lower() == name: + yield value + + def _takes_timeout(client): """! @@ -921,9 +940,10 @@ def process(self, flowdata): @param flowdata: the FlowData to process """ - # A sealed result redeems once, and a request bypasses_cache picks - # out carries evidence the cache key leaves out, so a request of - # either kind is neither served from the cache nor stored in it. + # A response to a request carrying a sealed result to redeem, or to + # one bypasses_cache picks out, is made for one visitor, so it is + # neither served from the cache nor stored in it. is_cacheable keeps + # out every other response made for one visitor. if hasattr(self, "cache") and ( humanconfidence.sealed_result_of( flowdata.evidence) is not None @@ -945,13 +965,14 @@ def bypasses_cache(evidence): """! Whether a request goes to the cloud service whatever the cache - holds, and its answer is not stored. The cache key is made from the - evidence keys the service lists, but the engine sends every evidence - value. A page iteration carries the session id and the sequence, - and a server may supply the visitor's JA4 and H2, none of which the - service lists. 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 the service waits for before it makes a 51Did, would + 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 request carrying any of Constants.UNCACHED_EVIDENCE_NAMES, under any prefix and in any letter case, bypasses the cache, and every other @@ -976,18 +997,28 @@ def bypasses_cache(evidence): def is_cacheable(self, data): """! - A response whose JSON has a top-level member named fodid, in any - case, holds a 51Did created for the one request that asked for it, - so it is neither stored in the cache nor served from it. A fodid - below the top level is not one, and a response that cannot be read - as a JSON object is cached as before. + A response made for one visitor is neither stored in the cache nor + served from it. That is a response whose JSON holds any of these, + with member names compared in any case. + + - A 51Did, being a top-level member named fodid. A fodid below the + top level is not one. + - A sealed Human Confidence result, being a HumanConfidence under + derived that humanconfidence.is_sealed_value finds sealed. + HumanConfidenceSource plays no part. + - The browser tests' script, being a BrowserTestsJavaScript under + browserderived that is not blank. + + A request made for one visitor never reaches the cache, as process + and bypasses_cache say. A response that cannot be read as a JSON + object is cached as before. @type data: ElementData @param data: A response the engine has just made, or one found in the cache @rtype: bool - @return: False if the response holds a fodid + @return: False if the response was made for one visitor """ try: @@ -997,7 +1028,17 @@ def is_cacheable(self, data): return True if not isinstance(answer, dict): return True - return not any(str(name).lower() == "fodid" for name in answer) + if any(str(name).lower() == Constants.DID_MEMBER for name in answer): + return False + if any(humanconfidence.is_sealed_value(value) + for value in _properties( + answer, Constants.HUMAN_CONFIDENCE_DATA_KEY, + Constants.HUMAN_CONFIDENCE_PROPERTY)): + return False + return all(humanconfidence.is_blank(value) + for value in _properties( + answer, Constants.BROWSER_TESTS_DATA_KEY, + Constants.BROWSER_TESTS_PROPERTY)) def report_properties_not_covered(self, result): 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 ac66f2ec..294ce704 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py @@ -145,12 +145,23 @@ class Constants: RESOURCE_PARAMETER, LICENSE_PARAMETER, LICENCE_SPELLING, VALUES_PARAMETER) - # Evidence names, under any prefix, that the service reads but does not - # list, so the cache key leaves them out. A request carrying one goes - # to the service whatever the cache holds. See + # Evidence names, under any prefix, that make a request one made for a + # single visitor, being the session id and the sequence of a page + # iteration and the visitor's JA4 and HTTP/2 settings. A request + # carrying one goes to the service whatever the cache holds. See # CloudRequestEngine.bypasses_cache. UNCACHED_EVIDENCE_NAMES = ("session-id", "sequence", "ja4", "h2") + # 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 + # properties under the data key of the element that gives them. + DID_MEMBER = "fodid" + HUMAN_CONFIDENCE_DATA_KEY = "derived" + HUMAN_CONFIDENCE_PROPERTY = "humanconfidence" + BROWSER_TESTS_DATA_KEY = "browserderived" + BROWSER_TESTS_PROPERTY = "browsertestsjavascript" + # Takes the place of the licence key in every message the engine # builds, and of the sealed result and the transaction in a message made # while a sealed result is redeemed. 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 7108ec69..02a819a5 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -77,6 +77,10 @@ # The values HumanConfidence has once a sealed result is redeemed. REDEEMED_VALUES = ("High", "Medium", "Low") +# The HumanConfidence values that are not a sealed result. Any other text +# that is not blank is one. See is_sealed_value. +UNSEALED_VALUES = ("High", "Medium", "Low") + # The values HumanConfidenceSource has once a sealed result is redeemed, as # the response gives them. The package reads them and never sets one. REDEEMED_SOURCES = ("Passive", "Active") @@ -203,6 +207,19 @@ def sealed_result_of(evidence): return str(value) +def is_sealed_value(value): + """! + Whether a HumanConfidence value the cloud service returned is a sealed + result, being text that is not blank and is none of UNSEALED_VALUES. + The value alone decides, never HumanConfidenceSource, because the route + a request takes decides sealing and a sealed result can be Passive or + Active. + """ + + return (isinstance(value, str) and not is_blank(value) + and value not in UNSEALED_VALUES) + + class HumanConfidencePage(object): """! diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py index d49db793..82614a18 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -21,9 +21,10 @@ # ********************************************************************* """ -A cache never stores or serves a Cloud Request Engine response that holds a -value created for one request, being a top-level member named fodid in any -case, as the caching page of the specification says. +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. """ import json @@ -39,6 +40,23 @@ from .classes.cloudrequestengine_testbase import CloudRequestEngineTestsBase from .classes.mockrequestclient import MockRequestClient +# A sealed result is text the browser can't read. Any text that is not blank +# and is none of High, Medium or Low is one. +SEALED = "3z|q7Lx0aB-mN2vR8sT4uW6yZ1cE5gI9kO" + +# The browser tests' script the page runs. +SCRIPT = "(function(){/* the browser tests */})();" + + +def human_confidence(value, source): + """A response holding HumanConfidence and HumanConfidenceSource under + derived, where source None leaves HumanConfidenceSource out.""" + + derived = {"humanconfidence": value} + if source is not None: + derived["humanconfidencesource"] = source + return {"device": {"ismobile": True}, "derived": derived} + class CountingClient(MockRequestClient): """Answers every data request with the same text and counts them.""" @@ -144,3 +162,68 @@ def test_an_entry_holding_a_fodid_is_not_served(self): served, requests = self.found_in_cache(entry_text) self.assertNotEqual(entry_text, served, name) self.assertEqual(1, requests, name) + + def test_a_sealed_passive_result_is_neither_stored_nor_served(self): + """A sealed result is told from the HumanConfidence value, so one + whose source is Passive is kept out of the cache as well.""" + + answer = json.dumps(human_confidence(SEALED, "Passive")) + self.assertEqual(2, self.requests_for(answer)) + served, requests = self.found_in_cache(answer) + self.assertNotEqual(answer, served) + self.assertEqual(1, requests) + + def test_a_sealed_result_is_kept_out_whatever_its_source(self): + for source in ("Active", None, "Unexpected"): + answer = json.dumps(human_confidence(SEALED, source)) + self.assertEqual(2, self.requests_for(answer), source) + + def test_a_sealed_result_is_found_in_any_case(self): + for data_key, name in (("Derived", "HumanConfidence"), + ("DERIVED", "humanConfidence")): + answer = json.dumps({data_key: {name: SEALED}}) + self.assertEqual(2, self.requests_for(answer), data_key) + + def test_an_unsealed_active_value_is_cached(self): + """Active does not mean sealed. A server's call with a License Key + gets the level itself, and nothing else in the response makes it + one made for one visitor.""" + + for level in ("High", "Medium", "Low"): + answer = json.dumps(human_confidence(level, "Active")) + self.assertEqual(1, self.requests_for(answer), level) + + def test_a_null_human_confidence_is_cached(self): + answer = json.dumps({"derived": { + "humanconfidence": None, + "humanconfidencenullreason": "No value for this request."}}) + self.assertEqual(1, self.requests_for(answer)) + + def test_a_blank_human_confidence_is_cached(self): + for blank in ("", " ", "\t\n"): + answer = json.dumps(human_confidence(blank, None)) + self.assertEqual(1, self.requests_for(answer), repr(blank)) + + def test_a_sealed_result_under_another_data_key_does_not_count(self): + answer = json.dumps({"device": {"humanconfidence": SEALED}}) + self.assertEqual(1, self.requests_for(answer)) + + def test_a_response_with_the_browser_tests_is_neither_stored_nor_served( + self): + for data_key, name in (("browserderived", "browsertestsjavascript"), + ("BrowserDerived", "BrowserTestsJavaScript")): + answer = json.dumps({data_key: {name: SCRIPT}}) + self.assertEqual(2, self.requests_for(answer), data_key) + served, requests = self.found_in_cache(answer) + self.assertNotEqual(answer, served, data_key) + self.assertEqual(1, requests, data_key) + + def test_a_response_without_the_browser_tests_script_is_cached(self): + """The property comes back with no value where the keys in use do + not cover it.""" + + for value in (None, "", " "): + answer = json.dumps({"browserderived": { + "browsertestsjavascript": value, + "browsertestsjavascriptnullreason": "Not covered."}}) + self.assertEqual(1, self.requests_for(answer), repr(value)) 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 3ffe375e..aa5c02bf 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 @@ -188,10 +188,10 @@ def test_the_server_supplies_the_visitors_connection(self): def test_every_iteration_reaches_the_cloud_through_a_cache(self): """The cache key is made from the evidence keys the cloud lists, - and the cloud lists none of the session id, the sequence, the - answers, the JA4 or the H2. So two iterations of one page share a - key, and without care the iteration carrying the answers would be - answered from the cache and never reach the cloud.""" + and the cloud lists neither the session id, the sequence nor the + answers. So two iterations of one page share a key, and without + care the iteration carrying the answers would be answered from the + cache and never reach the cloud.""" self.engine.set_cache(BasicDictionaryCache()) session_id = self.run_iterations(make_app(self.engine, True)) @@ -205,8 +205,8 @@ def test_every_iteration_reaches_the_cloud_through_a_cache(self): def test_a_supplied_connection_is_never_served_from_a_cache(self): """A server call with no page iteration, but with the visitor's - JA4 and H2, goes to the cloud each time, because the cloud judges - the call on them and the cache key leaves them out.""" + JA4 and H2, goes to the cloud each time, because a request carrying + them is made for one visitor.""" self.engine.set_cache(BasicDictionaryCache()) pipeline = PipelineBuilder({"add_javascript_builder": False}) \ From 8c5d40041b66ecf0f62a85b4c7a6c65044cced61 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 09:04:11 +0000 Subject: [PATCH 09/24] Count Unknown as a HumanConfidence value, not a sealed result HumanConfidence is published with the values High, Medium, Low and Unknown, so a sealed result is text that is not blank and is none of those four, letter case ignored. is_sealed_value treated Unknown as sealed and compared the other three in their exact case, so a response whose HumanConfidence was Unknown, or a published value in another case, was kept out of the response cache. UNSEALED_VALUES now holds the four published values in lower case and is_sealed_value compares the value in lower case. The cache tests cache Unknown with an Active source, Unknown with no source or a Passive one, and each published value in another letter case. The cloud request engine's tests pass with no keys set (195 passed, 2 skipped live licence key tests, 4 live tests deselected), and taking Unknown out of UNSEALED_VALUES fails two of the cache tests. --- .../humanconfidence.py | 16 ++++++++-------- .../tests/test_cloudrequestengine_cache.py | 15 +++++++++++++-- 2 files changed, 21 insertions(+), 10 deletions(-) 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 02a819a5..1c079644 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -77,9 +77,9 @@ # The values HumanConfidence has once a sealed result is redeemed. REDEEMED_VALUES = ("High", "Medium", "Low") -# The HumanConfidence values that are not a sealed result. Any other text -# that is not blank is one. See is_sealed_value. -UNSEALED_VALUES = ("High", "Medium", "Low") +# The values HumanConfidence is published with, in lower case. Any other +# text that is not blank is a sealed result. See is_sealed_value. +UNSEALED_VALUES = ("high", "medium", "low", "unknown") # The values HumanConfidenceSource has once a sealed result is redeemed, as # the response gives them. The package reads them and never sets one. @@ -210,14 +210,14 @@ def sealed_result_of(evidence): def is_sealed_value(value): """! Whether a HumanConfidence value the cloud service returned is a sealed - result, being text that is not blank and is none of UNSEALED_VALUES. - The value alone decides, never HumanConfidenceSource, because the route - a request takes decides sealing and a sealed result can be Passive or - Active. + result, being text that is not blank and is none of UNSEALED_VALUES, + letter case ignored. The value alone decides, never + HumanConfidenceSource, because the route a request takes decides + sealing and a sealed result can be Passive or Active. """ return (isinstance(value, str) and not is_blank(value) - and value not in UNSEALED_VALUES) + and value.lower() not in UNSEALED_VALUES) class HumanConfidencePage(object): diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py index 82614a18..9be4e47f 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -41,7 +41,7 @@ from .classes.mockrequestclient import MockRequestClient # A sealed result is text the browser can't read. Any text that is not blank -# and is none of High, Medium or Low is one. +# and is none of High, Medium, Low or Unknown, letter case ignored, is one. SEALED = "3z|q7Lx0aB-mN2vR8sT4uW6yZ1cE5gI9kO" # The browser tests' script the page runs. @@ -189,10 +189,21 @@ def test_an_unsealed_active_value_is_cached(self): gets the level itself, and nothing else in the response makes it one made for one visitor.""" - for level in ("High", "Medium", "Low"): + for level in ("High", "Medium", "Low", "Unknown"): answer = json.dumps(human_confidence(level, "Active")) self.assertEqual(1, self.requests_for(answer), level) + def test_a_published_value_in_any_case_is_cached(self): + """Unknown is one of the values HumanConfidence is published with, + so it is not a sealed result, and neither is any published value + in another letter case.""" + + for level, source in (("Unknown", None), ("Unknown", "Passive"), + ("unknown", None), ("HIGH", "Active"), + ("medium", "Passive"), ("lOW", None)): + answer = json.dumps(human_confidence(level, source)) + self.assertEqual(1, self.requests_for(answer), level) + def test_a_null_human_confidence_is_cached(self): answer = json.dumps({"derived": { "humanconfidence": None, From a0502f0d62d75aa78402fb57114b88c1a66fbc3b Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 10:17:32 +0000 Subject: [PATCH 10/24] Count Unknown as a sealed result, as HumanConfidence no longer has it HumanConfidence has the values High, Medium and Low only, so Unknown is text other than those and counts as a sealed result, which the response cache never stores or serves. This undoes the Unknown part of 8c5d4004. The letter case of a value is still ignored, as the rule says. UNSEALED_VALUES is back to high, medium and low. The cache tests no longer cache Unknown, and a new test checks that Unknown, with no source or a Passive or Active one and in lower case, is neither stored nor served. High, Medium and Low in another letter case are still cached. The cloud request engine's tests pass with no keys set (196 passed, 2 skipped live licence key tests, 4 live tests deselected), and putting Unknown back in UNSEALED_VALUES fails the new test. --- .../humanconfidence.py | 6 ++-- .../tests/test_cloudrequestengine_cache.py | 28 +++++++++++++------ 2 files changed, 22 insertions(+), 12 deletions(-) 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 1c079644..dffd08e2 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/humanconfidence.py @@ -77,9 +77,9 @@ # The values HumanConfidence has once a sealed result is redeemed. REDEEMED_VALUES = ("High", "Medium", "Low") -# The values HumanConfidence is published with, in lower case. Any other -# text that is not blank is a sealed result. See is_sealed_value. -UNSEALED_VALUES = ("high", "medium", "low", "unknown") +# The values HumanConfidence has, in lower case. Any other text that is not +# blank, Unknown included, is a sealed result. See is_sealed_value. +UNSEALED_VALUES = ("high", "medium", "low") # The values HumanConfidenceSource has once a sealed result is redeemed, as # the response gives them. The package reads them and never sets one. diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py index 9be4e47f..08c8a298 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -41,7 +41,7 @@ from .classes.mockrequestclient import MockRequestClient # A sealed result is text the browser can't read. Any text that is not blank -# and is none of High, Medium, Low or Unknown, letter case ignored, is one. +# and is none of High, Medium or Low, letter case ignored, is one. SEALED = "3z|q7Lx0aB-mN2vR8sT4uW6yZ1cE5gI9kO" # The browser tests' script the page runs. @@ -189,21 +189,31 @@ def test_an_unsealed_active_value_is_cached(self): gets the level itself, and nothing else in the response makes it one made for one visitor.""" - for level in ("High", "Medium", "Low", "Unknown"): + for level in ("High", "Medium", "Low"): answer = json.dumps(human_confidence(level, "Active")) self.assertEqual(1, self.requests_for(answer), level) - def test_a_published_value_in_any_case_is_cached(self): - """Unknown is one of the values HumanConfidence is published with, - so it is not a sealed result, and neither is any published value - in another letter case.""" + def test_a_value_in_any_case_is_cached(self): + """A value HumanConfidence has, in another letter case, is not a + sealed result.""" - for level, source in (("Unknown", None), ("Unknown", "Passive"), - ("unknown", None), ("HIGH", "Active"), - ("medium", "Passive"), ("lOW", None)): + for level, source in (("HIGH", "Active"), ("medium", "Passive"), + ("lOW", None)): answer = json.dumps(human_confidence(level, source)) self.assertEqual(1, self.requests_for(answer), level) + def test_unknown_is_neither_stored_nor_served(self): + """Unknown is not a value HumanConfidence has, so it is text other + than High, Medium or Low and counts as a sealed result.""" + + for level, source in (("Unknown", None), ("Unknown", "Passive"), + ("Unknown", "Active"), ("unknown", None)): + answer = json.dumps(human_confidence(level, source)) + self.assertEqual(2, self.requests_for(answer), level) + served, requests = self.found_in_cache(answer) + self.assertNotEqual(answer, served, level) + self.assertEqual(1, requests, level) + def test_a_null_human_confidence_is_cached(self): answer = json.dumps({"derived": { "humanconfidence": None, From afb8a908daaa561b5fbf5d591b89208967f52c2e Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 10:54:45 +0000 Subject: [PATCH 11/24] Read only High, Medium and Low as HumanConfidence values HumanConfidence's values are High, Medium and Low. The cloud engine listed Unknown as a fourth value, so a derived.humanconfidence of Unknown was handed on as the property's value. It now reads as missing, as any other text the property can't have does. The tests read Unknown with the other text that is not a value, with and without a sealed result, and no longer expect it to pass through. --- .../cloudengine.py | 4 ++-- .../tests/test_human_confidence.py | 11 ++++++----- 2 files changed, 8 insertions(+), 7 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 48f4c073..cc6e910e 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudengine.py @@ -43,8 +43,8 @@ "pipeline with a different one is refused. Build another cloud engine " "for this pipeline, or use the same Cloud Request Engine in both.") -# The values HumanConfidence can have. -HUMAN_CONFIDENCE_VALUES = ("High", "Medium", "Low", "Unknown") +# The values HumanConfidence can have. Unknown is not one of them. +HUMAN_CONFIDENCE_VALUES = ("High", "Medium", "Low") class OnPremiseMissingPropertyService(MissingPropertyService): diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py index 3122f018..88e07008 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py @@ -611,13 +611,14 @@ def test_without_a_sealed_result_the_response_is_read_as_before(self): self.assert_values(data, "Low", "Passive") self.assertNotIn("transaction", self.cloud.data_requests[-1]) - # HumanConfidence is only ever High, Medium, Low or Unknown, the values - # the property has, whatever text the cloud service returns. + # HumanConfidence is only ever High, Medium or Low, the values the + # property has, whatever text the cloud service returns. Unknown is not + # one of them. - OTHER_TEXT = ("hc1.eyJ2IjoxfQ.c2VhbGVk", "high", "", 3) + OTHER_TEXT = ("hc1.eyJ2IjoxfQ.c2VhbGVk", "high", "", 3, "Unknown") def test_a_sealed_request_gives_medium_for_any_other_text(self): - for value in self.OTHER_TEXT + ("Unknown",): + for value in self.OTHER_TEXT: for page, message in ((True, VALUE_NOT_KNOWN), (None, NO_TRANSACTION)): with self.subTest(value=value, page=page): @@ -647,7 +648,7 @@ def test_without_a_sealed_result_other_text_gives_no_value(self): self.assertEqual({}, dict(data.errors)) def test_without_a_sealed_result_each_value_is_read_unchanged(self): - for value in ("High", "Medium", "Low", "Unknown"): + for value in ("High", "Medium", "Low"): with self.subTest(value=value): self.cloud.answer = reply({"derived": { "humanconfidence": value, From 28052168f4494258a4cd392cc4499a36ec890072 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 12:11:52 +0000 Subject: [PATCH 12/24] BUILD: Restore the free-threaded tests' data files from the shared copy --- .github/workflows/free-threaded-python.yml | 75 ++++------------------ 1 file changed, 13 insertions(+), 62 deletions(-) diff --git a/.github/workflows/free-threaded-python.yml b/.github/workflows/free-threaded-python.yml index 6125a1e4..8c328e92 100644 --- a/.github/workflows/free-threaded-python.yml +++ b/.github/workflows/free-threaded-python.yml @@ -2,11 +2,10 @@ name: Free-threaded Python # Builds the Device Detection and IP Intelligence on-premise packages on the # free-threaded builds of Python and runs their tests there, with the free -# Lite data files. Those come from the assets common-ci fetches for each run, -# as every other workflow's tests do. The first job finds them in the asset -# cache, or fetches them into it with common-ci's prefetch_assets action when -# it misses, and the test jobs restore them from there. No job downloads -# them from the links in the data submodule. +# Lite data files. Those come from the one shared copy that common-ci's +# Nightly Shared Assets workflow downloads each day, as every other +# workflow's tests do, restored by common-ci's fetch-assets action. No job +# downloads them from the links in the data submodule. # ci/free-threaded-python.Tests.ps1 checks this. The native modules do not declare that they run without # the GIL, so Python turns the GIL back on when it loads them. # tests/test_free_threaded.py in each package checks that it does, and is @@ -45,55 +44,8 @@ env: _51DEGREES_WARNINGS_AS_ERRORS: 'true' jobs: - # The job is named Configure, as common-ci's is, because this repository's - # ci/fetch-assets.ps1 fetches the assets of every product only in a job of - # that name. The asset cache it fills is the one the other workflows that - # day restore, so it must never hold only some of them. - Configure: - name: Find or fetch the run's assets - runs-on: ubuntu-latest - outputs: - key: ${{ steps.prefetch-assets.outputs.cache-key }} - defaults: - run: - shell: pwsh - steps: - # common-ci's action and steps run from its checkout, with this - # repository below it, as in common-ci's own workflows. - - name: Checkout common-ci - uses: actions/checkout@v4 - with: - repository: 51Degrees/common-ci - ref: main - persist-credentials: false - - # The fetch links the assets into the data submodule, so it is - # checked out too. - - name: Checkout repository - uses: actions/checkout@v4 - with: - path: ${{ github.event.repository.name }} - persist-credentials: false - submodules: recursive - - # Restores nothing, and fetches the assets into the cache only when it - # has no copy under the day's key. - # The action is handed no secrets, because GitHub marks a workflow that - # hands every secret to a step as possibly malicious and holds each run - # for approval. The fetch reads only the data file license key, which - # goes as license-key. - - name: Find or fetch the assets - id: prefetch-assets - uses: ./.github/actions/prefetch_assets - with: - repo: ${{ github.event.repository.name }} - secrets: '{}' - vars: ${{ toJSON(vars) }} - license-key: ${{ secrets.LICENSE_KEY_V4TAC_IPIV4ENTERPRISE }} - free-threaded: name: Python ${{ matrix.python }} on ${{ matrix.os }} - needs: Configure strategy: fail-fast: false matrix: @@ -167,17 +119,16 @@ jobs: -e device-detection/fiftyone_devicedetection ` -e device-detection/fiftyone_devicedetection_examples - # The path and the cross-OS setting are those prefetch_assets saves - # with, so the key matches. - - name: Restore the run's assets - uses: actions/cache/restore@v5 + # The free files need no key. A file the shared copy lacks fails the + # step, and nothing downloads it here. + - name: Restore the free data files + uses: 51Degrees/common-ci/actions/fetch-assets@main with: - path: assets - key: ${{ needs.Configure.outputs.key }} - enableCrossOsArchive: true - # The first job fetched them, so a miss is a fault, never a reason - # to download them here. - fail-on-cache-miss: true + assets: | + 51Degrees-LiteV4.1.hash + 20000 Evidence Records.yml + 51Degrees-IPIV4AsnIpiV41.ipi + 51Degrees-LiteIpiV41.ipi # Copies, not links, so the Windows job needs no right to make links. - name: Put the free data files where the tests look for them From 5de373f51d3cc5f02d64065be896de541048d315 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 12:11:55 +0000 Subject: [PATCH 13/24] TEST: Expect the free-threaded tests to restore the shared copy, with no cache --- ci/free-threaded-python.Tests.ps1 | 78 ++++++++----------------------- 1 file changed, 19 insertions(+), 59 deletions(-) diff --git a/ci/free-threaded-python.Tests.ps1 b/ci/free-threaded-python.Tests.ps1 index 848a3aa3..86d14b27 100644 --- a/ci/free-threaded-python.Tests.ps1 +++ b/ci/free-threaded-python.Tests.ps1 @@ -1,7 +1,8 @@ # Tests that .github/workflows/free-threaded-python.yml takes the free Lite -# data files from the assets common-ci fetches for each run, in one job, and -# that the jobs that test restore them from that job's cache, rather than any -# job downloading them from the links in the data submodule. +# data files from the one shared copy that common-ci's Nightly Shared Assets +# workflow downloads each day, restored in each job that tests by common-ci's +# fetch-assets step, rather than any job downloading them from the links in +# the data submodule or keeping them in this repository's Actions cache. # The workflow is read as text, as the runners have no YAML module. BeforeAll { @@ -52,10 +53,10 @@ BeforeAll { } } - $script:Fetching = @($script:Jobs.Keys | Where-Object { - ($script:Jobs[$_] -join "`n") -match 'uses:\s*\S*prefetch_assets' }) $script:Testing = @($script:Jobs.Keys | Where-Object { ($script:Jobs[$_] -join "`n") -match 'pytest' }) + $script:FreeFiles = @('51Degrees-LiteV4.1.hash', '20000 Evidence Records.yml', + '51Degrees-IPIV4AsnIpiV41.ipi', '51Degrees-LiteIpiV41.ipi') } Describe 'free-threaded-python.yml' { @@ -63,73 +64,32 @@ Describe 'free-threaded-python.yml' { $script:Text | Should -Not -Match 'get-data-files' } - It 'finds or fetches the assets in one job only' { - $script:Fetching.Count | Should -Be 1 - } - - It 'names that job Configure, so every product''s assets are fetched' { - # ci/fetch-assets.ps1 fetches every product's assets only in a job of - # that name, and the cache it fills is shared with the other - # workflows. - $script:Fetching[0] | Should -BeExactly 'Configure' - Get-Content -Raw (Join-Path $PSScriptRoot 'fetch-assets.ps1') | - Should -Match "GITHUB_JOB\s+-eq\s+'Configure'" - } - - It 'fetches with common-ci''s action, run from common-ci''s checkout' { - $job = $script:Fetching[0] - $prefetch = @(Get-Step $job './.github/actions/prefetch_assets') - $prefetch.Count | Should -Be 1 - Get-Value $prefetch[0] 'id' | Should -Not -BeNullOrEmpty - Get-Value $prefetch[0] 'license-key' | Should -Not -BeNullOrEmpty - $checkouts = @(Get-Step $job 'actions/checkout') - @($checkouts | Where-Object { - (Get-Value $_ 'repository') -eq '51Degrees/common-ci' -and - -not (Get-Value $_ 'path') }).Count | Should -Be 1 - $own = @($checkouts | Where-Object { -not (Get-Value $_ 'repository') }) - $own.Count | Should -Be 1 - Get-Value $own[0] 'path' | Should -Be (Get-Value $prefetch[0] 'repo') - Get-Value $own[0] 'submodules' | Should -Be 'recursive' + It 'keeps nothing in the Actions cache and runs no prefetch' { + $script:Text | Should -Not -Match 'actions/cache|prefetch_assets' } It 'hands no step every secret, so GitHub does not hold its runs' { # GitHub holds each run of a workflow that hands every secret to a # step for approval, and the run never starts on its own. $script:Text | Should -Not -Match 'toJSON\(\s*secrets\s*\)' - $prefetch = @(Get-Step $script:Fetching[0] './.github/actions/prefetch_assets') - Get-Value $prefetch[0] 'secrets' | Should -BeExactly "'{}'" - } - - It 'gives the cache key to the jobs that test' { - $job = $script:Fetching[0] - $id = Get-Value (@(Get-Step $job './.github/actions/prefetch_assets')[0]) 'id' - ($script:Jobs[$job] -join "`n") | Should -Match ( - '\n outputs:\s*\n\s+key:\s*' + - [regex]::Escape('${{ steps.' + $id + '.outputs.cache-key }}')) } - It 'never fetches in a job that runs the tests' { + It 'restores the free files from the shared copy in each job that runs the tests' { $script:Testing.Count | Should -BeGreaterThan 0 - foreach ($job in $script:Testing) { - $script:Fetching | Should -Not -Contain $job - } - } - - It 'restores the assets in each job that runs the tests, as prefetch_assets saves them' { - $job = $script:Fetching[0] foreach ($testing in $script:Testing) { - $text = $script:Jobs[$testing] -join "`n" - $text | Should -Match "\n needs:\s*\[?\s*$([regex]::Escape($job))\b" - $restore = @(Get-Step $testing 'actions/cache/restore') + $restore = @(Get-Step $testing '51Degrees/common-ci/actions/fetch-assets') $restore.Count | Should -Be 1 - Get-Value $restore[0] 'path' | Should -Be 'assets' - Get-Value $restore[0] 'key' | - Should -Be ('${{ needs.' + $job + '.outputs.key }}') - Get-Value $restore[0] 'fail-on-cache-miss' | Should -Be 'true' - Get-Value $restore[0] 'enableCrossOsArchive' | Should -Be 'true' + $text = $restore[0] -join "`n" + foreach ($file in $script:FreeFiles) { + $text | Should -Match "(?m)^\s+$([regex]::Escape($file))\s*$" + } + # The free files need no key, and nothing is downloaded or kept. + $text | Should -Not -Match 'encryption-key|cache:|lazy:' + $jobText = $script:Jobs[$testing] -join "`n" + $jobText.IndexOf('common-ci/actions/fetch-assets') | + Should -BeLessThan $jobText.IndexOf('- name: Put the free data files where the tests look for them') } } - It 'puts each free data file the tests use in place from the assets' { foreach ($testing in $script:Testing) { $text = $script:Jobs[$testing] -join "`n" From f08ed66763cb8cf6c6aa38faf630bb923baa15ed Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 13:33:41 +0000 Subject: [PATCH 14/24] BUILD: Restore the published examples' data files from the shared copy --- .github/workflows/examples-published.yml | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml index 476f00a3..29ce434f 100644 --- a/.github/workflows/examples-published.yml +++ b/.github/workflows/examples-published.yml @@ -97,13 +97,13 @@ jobs: with: python-version: '3.14' - # The free data files, from the assets common-ci fetches and keeps in - # the Actions cache for the day, so nothing follows the links here. - - name: Fetch the free data files + # The free data files, from the one shared copy that common-ci's + # Nightly Shared Assets workflow downloads each day, so nothing follows + # the links here. + - name: Restore the free data files if: steps.keys.outputs.run == 'true' uses: 51Degrees/common-ci/actions/fetch-assets@main with: - cache: 'true' assets: | 51Degrees-LiteV4.1.hash 20000 Evidence Records.yml @@ -111,15 +111,14 @@ jobs: 51Degrees-LiteIpiV41.ipi # The Device Detection tests of the data file update example serve a - # copy of the TAC data file. It comes from the Distributor with the - # data license, which common-ci's fetch reads as - # _51DEGREES_LICENSE_KEY and fails without. The file is licensed, so - # it is not kept in the Actions cache. - - name: Fetch the TAC data file + # copy of the TAC data file. It comes from the same shared copy, + # decrypted with CACHE_ENCRYPTION_KEY, which common-ci's step reads + # from this step's environment. Nothing here keeps it. + - name: Restore the TAC data file if: steps.keys.outputs.run == 'true' uses: 51Degrees/common-ci/actions/fetch-assets@main env: - _51DEGREES_LICENSE_KEY: ${{ secrets.LICENSE_KEY_V4TAC_IPIV4ENTERPRISE }} + CACHE_ENCRYPTION_KEY: ${{ secrets.CACHE_ENCRYPTION_KEY }} with: assets: TAC-HashV41.hash From 03ee2948d4cb3e948d24768dfb81e1581b058ace Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 13:42:58 +0000 Subject: [PATCH 15/24] BUILD: List CACHE_ENCRYPTION_KEY among the names only CI uses --- ci/check-environment-variable-names.ps1 | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ci/check-environment-variable-names.ps1 b/ci/check-environment-variable-names.ps1 index e3f4edbc..694469ce 100644 --- a/ci/check-environment-variable-names.ps1 +++ b/ci/check-environment-variable-names.ps1 @@ -35,8 +35,10 @@ $script:PlatformNames = @( $script:PlatformPrefixes = @('GITHUB_') # The names only CI uses. No customer sets them, so they have no _51DEGREES_ -# prefix, and each name says what it holds. -$script:CiNames = @('CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING') +# prefix, and each name says what it holds. CACHE_ENCRYPTION_KEY decrypts the +# licensed files of common-ci's shared copy of the data files, and a workflow +# gives it to common-ci's fetch-assets step in that step's environment. +$script:CiNames = @('CACHE_ENCRYPTION_KEY', 'CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING') $name = '(?[A-Za-z0-9_]+)' $quoted = "['`"]$name['`"]" From 8f8bb720f0229e8b2f218ed984722c9270e3aeb3 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 16:33:20 +0000 Subject: [PATCH 16/24] 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) From 8f18579fb9bcd3bbc246e496d358db6593d91e5b Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 18:05:18 +0000 Subject: [PATCH 17/24] 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 18/24] 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 19/24] 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 20/24] 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 21/24] 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 22/24] 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 23/24] 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() From 71f274a8c9ccc619f2e20372d24e5c232aaee1a4 Mon Sep 17 00:00:00 2001 From: James Rosewell Date: Tue, 1 Dec 2026 20:00:03 +0000 Subject: [PATCH 24/24] Let a subclass of LRUEngineCache that skips its constructor read and write LRUEngineCache gained a lock in its constructor. A subclass whose own constructor sets the cache without calling that constructor had no lock, so its first read or write raised AttributeError. The lock is now made on first use when the constructor did not make it, once per cache however many threads ask at the same time. Two tests cover a subclass that skips the constructor. Both fail without the change. --- .../fiftyone_pipeline_engines/lru_cache.py | 22 ++++++++++++-- .../tests/test_lru_cache.py | 30 +++++++++++++++++++ 2 files changed, 50 insertions(+), 2 deletions(-) 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 43208946..7e01b804 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 @@ -33,6 +33,11 @@ class LRUEngineCache(DataKeyedCache): one thread at a time reads or writes the cache, which lets requests processed on several threads share it. """ + + # Held only while a cache makes its own lock, for a subclass whose + # constructor sets the cache without calling this constructor. + _making_lock = threading.Lock() + def __init__(self, size = 1000): """! Constructor for LRUCache @@ -43,12 +48,25 @@ def __init__(self, size = 1000): self.cache = LRUCache(maxsize=size) self._lock = threading.Lock() + def _get_lock(self): + + # A subclass may not have called the constructor, so the lock is + # made on first use, once, however many threads ask at the same time. + lock = getattr(self, "_lock", None) + if lock is None: + with LRUEngineCache._making_lock: + lock = getattr(self, "_lock", None) + if lock is None: + lock = threading.Lock() + self._lock = lock + return lock + def get_cache_value (self, cache_key): - with self._lock: + with self._get_lock(): return self.cache.get(cache_key) def set_cache_value(self, key, value): - with self._lock: + with self._get_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 index 4788c52b..a25f76d3 100644 --- a/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py +++ b/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py @@ -164,5 +164,35 @@ def work(number): self.assertIsNone(cache.get_cache_value(0)) +class OwnCacheEngineCache(LRUEngineCache): + """A subclass that sets its cache itself and does not call the + constructor of LRUEngineCache.""" + + def __init__(self, cache): + self.cache = cache + + +class SubclassWithoutConstructorTests(unittest.TestCase): + + def test_a_subclass_that_skips_the_constructor_reads_and_writes(self): + cache = OwnCacheEngineCache(LRUCache(maxsize=CACHE_SIZE)) + cache.set_cache_value(1, value_of(1)) + self.assertEqual(value_of(1), cache.get_cache_value(1)) + self.assertIsNone(cache.get_cache_value(2)) + + def test_its_threads_share_one_lock_made_on_first_use(self): + recording = OverlapRecordingCache(CACHE_SIZE) + cache = OwnCacheEngineCache(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) + + if __name__ == "__main__": unittest.main()