diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml new file mode 100644 index 00000000..dc5660a5 --- /dev/null +++ b/.github/workflows/examples-published.yml @@ -0,0 +1,363 @@ +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, +# 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 +# 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, 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: + 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 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: + assets: | + 51Degrees-LiteV4.1.hash + 20000 Evidence Records.yml + 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 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: + CACHE_ENCRYPTION_KEY: ${{ secrets.CACHE_ENCRYPTION_KEY }} + 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 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' + $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" + 'TAC-HashV41.hash' = "$dd/TAC-HashV41.hash" + '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 + } + Move-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. + # + # 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 + } + "$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, 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: + _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 --continue-on-collection-errors ` + "--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) 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 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['`"]" 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" 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..791d8656 --- /dev/null +++ b/device-detection/fiftyone_devicedetection_cloud/tests/test_builder_cache.py @@ -0,0 +1,130 @@ +# ********************************************************************* +# 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) + + 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/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 48f4c073..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 " @@ -43,8 +47,16 @@ "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") + +# 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): @@ -77,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): """! @@ -86,6 +101,45 @@ def get_evidence_key_filter(self): return BasicListEvidenceKeyFilter([]) + def set_cache(self, cache): + + """! + 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 + """ + + 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): + + """! + 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/cloudrequestengine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py index ce672932..fdb61810 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): """! @@ -97,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". @@ -538,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] @@ -921,10 +973,14 @@ def process(self, flowdata): @param flowdata: the FlowData to process """ - # A sealed result redeems once, so a request that carries one is - # neither served from the cache nor stored in it. - if (hasattr(self, "cache") and humanconfidence.sealed_result_of( - flowdata.evidence) is not None): + # 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 + or self.bypasses_cache(flowdata.evidence)): self.process_internal(flowdata) result = None else: @@ -937,21 +993,65 @@ 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. 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 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. + + @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): """! - 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: @@ -961,7 +1061,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 c16679c6..01d2e1a0 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py @@ -145,6 +145,31 @@ class Constants: RESOURCE_PARAMETER, LICENSE_PARAMETER, LICENCE_SPELLING, VALUES_PARAMETER) + # 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 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 + # 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..595999bc 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 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. 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, + 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.lower() not in UNSEALED_VALUES) + + class HumanConfidencePage(object): """! @@ -321,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 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 new file mode 100644 index 00000000..8589d326 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudengine_cache.py @@ -0,0 +1,184 @@ +# ********************************************************************* +# 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 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 +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.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 + 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 pipeline_with(self, engine, logger=None): + builder = PipelineBuilder({ + "add_javascript_builder": False, + "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 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", "first"], self.values_of(pipeline)) + self.assertEqual([], engine.cache.calls) + + +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 d49db793..8d7a68bd 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine_cache.py @@ -21,9 +21,13 @@ # ********************************************************************* """ -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, 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. 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 @@ -39,6 +43,34 @@ 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, letter case ignored, is one. +SEALED = "3z|q7Lx0aB-mN2vR8sT4uW6yZ1cE5gI9kO" + +# 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 + 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.""" @@ -57,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.""" @@ -84,12 +135,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") @@ -144,3 +198,179 @@ 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_value_in_any_case_is_cached(self): + """A value HumanConfidence has, in another letter case, is not a + sealed result.""" + + 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, + "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)) + + 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")) + + 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) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_human_confidence.py index 3122f018..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.""" @@ -122,7 +141,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 +158,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 +441,46 @@ def test_two_reads_make_one_request(self): self.assertEqual(first, second) self.assertEqual(1, len(self.cloud.data_requests)) + def test_derived_cloud_ignores_a_cache_with_one_warning(self): + derived = DerivedCloud() + 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([], cache.calls) + def test_a_request_with_a_sealed_result_skips_the_cache(self): cache = BasicDictionaryCache() pipeline = self.pipeline(cache=cache) @@ -611,13 +671,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 +708,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, 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..2d4c0500 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_server_route_pass_through.py @@ -0,0 +1,335 @@ +# ********************************************************************* +# 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 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 +from fiftyone_pipeline_engines.basic_dictionary_cache import ( + BasicDictionaryCache) + +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. 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|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%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 + 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 = WireClient() + 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 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) + 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. 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() + 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]) + + 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 + 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_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 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)) + 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 a request carrying + them is made for one visitor.""" + + 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.""" + + 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() 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 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..7753174a 100644 --- a/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py +++ b/pipeline/fiftyone_pipeline_core/tests/test_javascriptbuilder_object_name.py @@ -93,9 +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): 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..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 @@ -20,14 +20,24 @@ # 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. """ + + # 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 @@ -36,10 +46,27 @@ 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): - return self.cache.get(cache_key) + with self._get_lock(): + return self.cache.get(cache_key) def set_cache_value(self, key, value): - self.cache.__setitem__(key, value) + + 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 new file mode 100644 index 00000000..a25f76d3 --- /dev/null +++ b/pipeline/fiftyone_pipeline_engines/tests/test_lru_cache.py @@ -0,0 +1,198 @@ +# ********************************************************************* +# 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)) + + +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()