diff --git a/.github/workflows/free-threaded-python.yml b/.github/workflows/free-threaded-python.yml index be4a347e..de61010e 100644 --- a/.github/workflows/free-threaded-python.yml +++ b/.github/workflows/free-threaded-python.yml @@ -2,9 +2,11 @@ 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. The first job downloads those once for each commit of the -# data submodule, which links them, and puts them in the cache. The test jobs -# restore them from there and never download them. +# 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. # 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 @@ -37,54 +39,51 @@ permissions: contents: read jobs: - free-data-files: - name: Fetch the free Lite data files once + # 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.key.outputs.key }} + 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 - - name: Name the cache after the data submodule - id: key - run: | - # The data submodule's .link files say which files are fetched and - # from where, so a new commit of it needs the files again. Change - # v2 when the list of files below changes. - $data = git -C cxx rev-parse HEAD:data - if ($LASTEXITCODE) { exit $LASTEXITCODE } - "key=free-lite-data-v2-$data" >> $env:GITHUB_OUTPUT - - - name: Look for the files in the cache - id: cache - uses: actions/cache@v4 + # Restores nothing, and fetches the assets into the cache only when it + # has no copy under the day's key. + - name: Find or fetch the assets + id: prefetch-assets + uses: ./.github/actions/prefetch_assets with: - path: | - cxx/data/**/51Degrees-LiteV4.1.hash - cxx/data/**/20000 Evidence Records.yml - cxx/data/**/51Degrees-LiteV41.ipi - cxx/data/**/51Degrees-IPIV4AsnIpiV41.ipi - key: ${{ steps.key.outputs.key }} - # The Windows job restores what this Linux job saves. - enableCrossOsArchive: true - lookup-only: true - - # Runs only when the cache has no copy, and the cache saves the files - # when the job ends. - - name: Fetch the free Lite data files - if: steps.cache.outputs.cache-hit != 'true' - run: ./cxx/data/get-data-files.ps1 51Degrees-LiteV4.1.hash '20000 Evidence Records.yml' 51Degrees-LiteV41.ipi 51Degrees-IPIV4AsnIpiV41.ipi + repo: ${{ github.event.repository.name }} + secrets: ${{ toJSON(secrets) }} + vars: ${{ toJSON(vars) }} + license-key: ${{ secrets.LICENSE_KEY_V4TAC_IPIV4ENTERPRISE }} free-threaded: name: Python ${{ matrix.python }} on ${{ matrix.os }} - needs: free-data-files + needs: Configure strategy: fail-fast: false matrix: @@ -158,26 +157,32 @@ jobs: -e device-detection/fiftyone_devicedetection ` -e device-detection/fiftyone_devicedetection_examples - - name: Restore the free Lite data files - uses: actions/cache/restore@v4 + # 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 with: - path: | - cxx/data/**/51Degrees-LiteV4.1.hash - cxx/data/**/20000 Evidence Records.yml - cxx/data/**/51Degrees-LiteV41.ipi - cxx/data/**/51Degrees-IPIV4AsnIpiV41.ipi - key: ${{ needs.free-data-files.outputs.key }} + 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 - - name: Put the IP Intelligence file where the tests look for it + # 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 run: | - New-Item -ItemType Directory -Force -Path ip-intelligence/assets | Out-Null - New-Item -ItemType HardLink ` - -Path ip-intelligence/assets/51Degrees-LiteIpiV41.ipi ` - -Target cxx/data/ip-intelligence/51Degrees-LiteV41.ipi | Out-Null + $dd = 'cxx/data/device-detection' + $ipi = 'cxx/data/ip-intelligence' + New-Item -ItemType Directory -Force -Path $dd, $ipi, ip-intelligence/assets | Out-Null + Copy-Item -LiteralPath 'assets/51Degrees-LiteV4.1.hash' -Destination $dd + Copy-Item -LiteralPath 'assets/20000 Evidence Records.yml' -Destination $dd + Copy-Item -LiteralPath 'assets/51Degrees-IPIV4AsnIpiV41.ipi' -Destination $ipi + # The data repository saves the Lite IP Intelligence file as + # 51Degrees-LiteV41.ipi, and the tests also look for it under the + # name the assets give it. + Copy-Item -LiteralPath 'assets/51Degrees-LiteIpiV41.ipi' -Destination "$ipi/51Degrees-LiteV41.ipi" + Copy-Item -LiteralPath 'assets/51Degrees-LiteIpiV41.ipi' -Destination ip-intelligence/assets - name: Build the native modules run: | diff --git a/ci/free-threaded-python.Tests.ps1 b/ci/free-threaded-python.Tests.ps1 index 8f95fe3f..d2d55118 100644 --- a/ci/free-threaded-python.Tests.ps1 +++ b/ci/free-threaded-python.Tests.ps1 @@ -1,12 +1,14 @@ -# Tests that .github/workflows/free-threaded-python.yml fetches the free Lite -# data files once, in one job, and that the jobs that test take them from the -# cache that job fills, rather than each downloading them again. +# 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. # The workflow is read as text, as the runners have no YAML module. BeforeAll { $script:Workflow = Join-Path $PSScriptRoot '..' '.github' 'workflows' ` 'free-threaded-python.yml' $lines = @(Get-Content -LiteralPath $script:Workflow) + $script:Text = $lines -join "`n" # Each job's lines, by the job's name, from the two-space keys under jobs. $script:Jobs = [ordered]@{} @@ -41,22 +43,7 @@ BeforeAll { } if ($null -ne $current) { $steps += , $current } return @($steps | Where-Object { - ($_ -join "`n") -match "uses:\s*$([regex]::Escape($Uses))@" }) - } - - # The lines of a "path: |" block in a step, trimmed. - function Get-Paths($Step) { - $paths = @() - $inPaths = $false - foreach ($line in $Step) { - if ($line -match '^\s+path:\s*\|\s*$') { $inPaths = $true; continue } - if ($inPaths -and $line -match '^\s{12,}\S') { - $paths += $line.Trim() - continue - } - $inPaths = $false - } - return $paths + ($_ -join "`n") -match "(?m)uses:\s*$([regex]::Escape($Uses))(@|\s*$)" }) } function Get-Value($Step, [string]$Key) { @@ -66,66 +53,83 @@ BeforeAll { } $script:Fetching = @($script:Jobs.Keys | Where-Object { - ($script:Jobs[$_] -join "`n") -match 'get-data-files\.ps1' }) + ($script:Jobs[$_] -join "`n") -match 'uses:\s*\S*prefetch_assets' }) $script:Testing = @($script:Jobs.Keys | Where-Object { ($script:Jobs[$_] -join "`n") -match 'pytest' }) } Describe 'free-threaded-python.yml' { - It 'downloads the free data files in one job only' { + It 'never downloads from the links in the data submodule' { + $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 'downloads them in a job that is not a matrix' { - foreach ($job in $script:Fetching) { - ($script:Jobs[$job] -join "`n") | Should -Not -Match 'matrix:' - } + 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 '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 downloads them in a job that runs the tests' { + It 'never fetches in a job that runs the tests' { $script:Testing.Count | Should -BeGreaterThan 0 foreach ($job in $script:Testing) { $script:Fetching | Should -Not -Contain $job } } - It 'saves them in the cache, and downloads them only when it misses' { + It 'restores the assets in each job that runs the tests, as prefetch_assets saves them' { $job = $script:Fetching[0] - $cache = @(Get-Step $job 'actions/cache') - $cache.Count | Should -Be 1 - Get-Value $cache[0] 'id' | Should -Not -BeNullOrEmpty - $id = Get-Value $cache[0] 'id' - $fetch = ($script:Jobs[$job] -join "`n") - $fetch | Should -Match ("if:\s*steps\.$id\.outputs\.cache-hit\s*!=\s*" + - "'true'\s*\n\s+run:\s*[|]?\s*\n?\s*\./cxx/data/get-data-files\.ps1") - } - - It 'restores them in each job that runs the tests, from the same key and paths' { - $job = $script:Fetching[0] - $save = @(Get-Step $job 'actions/cache')[0] - $keyStep = Get-Value $save 'key' - $keyStep | Should -Match '^\$\{\{\s*steps\.([\w-]+)\.outputs\.key\s*\}\}$' - ($script:Jobs[$job] -join "`n") | Should -Match ( - '\n outputs:\s*\n\s+key:\s*' + [regex]::Escape($keyStep)) 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.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-Paths $restore[0] | Should -Be (Get-Paths $save) + Get-Value $restore[0] 'enableCrossOsArchive' | Should -Be 'true' } } - It 'saves and restores across operating systems, for the Windows jobs' { - $job = $script:Fetching[0] - $steps = @(Get-Step $job 'actions/cache') + @($script:Testing | - ForEach-Object { Get-Step $_ 'actions/cache/restore' }) - $steps.Count | Should -BeGreaterThan 1 - foreach ($step in $steps) { - Get-Value $step 'enableCrossOsArchive' | Should -Be 'true' + 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" + foreach ($file in '51Degrees-LiteV4.1.hash', '20000 Evidence Records.yml', + '51Degrees-IPIV4AsnIpiV41.ipi', '51Degrees-LiteIpiV41.ipi') { + $text | Should -Match ([regex]::Escape("assets/$file")) + } + $text | Should -Match ([regex]::Escape('51Degrees-LiteV41.ipi')) } } @@ -162,15 +166,4 @@ Describe 'free-threaded-python.yml' { '\s*\n(\s+\S.*\n)*?\s+\$PSNativeCommandUseErrorActionPreference = \$true') } } - - It 'caches each of the free data files the tests use' { - $paths = Get-Paths (@(Get-Step $script:Fetching[0] 'actions/cache')[0]) - foreach ($file in '51Degrees-LiteV4.1.hash', '51Degrees-LiteV41.ipi', - '51Degrees-IPIV4AsnIpiV41.ipi', '20000 Evidence Records.yml') { - $paths | Should -Contain "cxx/data/**/$file" - } - # The evidence is the YAML file, and no other evidence file is cached. - @($paths | Where-Object { $_ -notmatch '\.(hash|ipi|yml)$' }) | - Should -BeNullOrEmpty - } } diff --git a/device-detection/fiftyone_devicedetection_examples/tests/data_update_standin.py b/device-detection/fiftyone_devicedetection_examples/tests/data_update_standin.py new file mode 100644 index 00000000..627fdfc0 --- /dev/null +++ b/device-detection/fiftyone_devicedetection_examples/tests/data_update_standin.py @@ -0,0 +1,218 @@ +# ********************************************************************* +# 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 stand-in for the Distributor on this machine, so a test of the data file +update example never reaches the Distributor and needs no real licence key. + +It answers as the Distributor does for a licence key that holds several +products, whatever key it is sent: + +- a request that names no product gets 300 with the list of products, and a + Location header naming the first +- a request for a product not on the list gets 403 +- a request for a product on the list gets the data file to serve, gzipped + and with the MD5 hash of what is sent as lower case hexadecimal, unless the + request's If-Modified-Since is not earlier than the file's published date, + when it gets 304 + +Every request is recorded with the product it named and the status it got. +""" + +import functools +import gzip +import hashlib +import http.server +import json +import shutil +import struct +import threading +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from email.utils import parsedate_to_datetime +from unittest import mock +from urllib.parse import parse_qsl, quote, urlsplit, urlunsplit + +import requests + +# Where the published date starts in the header of a Hash data file: a 16 +# bit year, little endian, then a byte each for the month and the day. +PUBLISHED_OFFSET = 66 + +# The address the examples ask for an update, which only the stand-in +# answers while a test runs. +DISTRIBUTOR_HOST = "distributor.51degrees.com" + +NOT_OFFERED = ('{"Error":"The license key provided does not contain the ' + 'requested product."}') + +SEVERAL_PRODUCTS = ("There are multiple products associated with this " + "license key. Please use the URI returned in the " + "Location header.") + + +def read_published(path): + """The published date in a data file's header.""" + with open(path, "rb") as file: + file.seek(PUBLISHED_OFFSET) + year, month, day = struct.unpack("= self.published + + +class Handler(http.server.BaseHTTPRequestHandler): + def __init__(self, stand_in, *args, **kwargs): + self.stand_in = stand_in + super().__init__(*args, **kwargs) + + def log_message(self, format, *args): + pass + + def do_GET(self): + stand_in = self.stand_in + product = product_of(urlsplit(self.path).query) + requested = stand_in.url.split("/api/")[0] + self.path + if product is None: + uris = [with_product(requested, offered) + for offered in stand_in.products] + stand_in.record(None, 300) + self.answer(300, json.dumps({ + "AvailableUris": uris, + "Error": SEVERAL_PRODUCTS, + }).encode(), "application/json", {"Location": uris[0]}) + elif product.lower() not in (p.lower() for p in stand_in.products): + stand_in.record(product, 403) + self.answer(403, NOT_OFFERED.encode(), "application/json") + elif stand_in.not_modified(self.headers.get("If-Modified-Since")): + stand_in.record(product, 304) + self.send_response(304) + self.end_headers() + else: + stand_in.record(product, 200) + self.answer(200, stand_in.compressed, "application/octet-stream", + {"Content-MD5": stand_in.md5}) + + def answer(self, status, body, content_type, headers=None): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + for name, value in (headers or {}).items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(body) + + +@contextmanager +def serving(products, data_file): + """Serves the data file as the Distributor would for a licence key that + holds the products, and sends every request the data file update service + makes to the Distributor to it instead. Gives the stand-in, whose + requests a test checks.""" + stand_in = StandIn(products, data_file) + server = http.server.ThreadingHTTPServer( + ("127.0.0.1", 0), functools.partial(Handler, stand_in)) + stand_in.url = (f"http://127.0.0.1:{server.server_address[1]}" + "/api/v2/download") + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + real_get = requests.get + + def fake_get(url, *args, **kwargs): + parts = urlsplit(url) + if parts.hostname == DISTRIBUTOR_HOST: + url = stand_in.url + ("?" + parts.query if parts.query else "") + return real_get(url, *args, **kwargs) + + try: + with mock.patch.object(requests, "get", fake_get): + yield stand_in + finally: + server.shutdown() + server.server_close() diff --git a/device-detection/fiftyone_devicedetection_examples/tests/test_onpremiseexamples.py b/device-detection/fiftyone_devicedetection_examples/tests/test_onpremiseexamples.py index b12f7c5e..9bea1cb5 100644 --- a/device-detection/fiftyone_devicedetection_examples/tests/test_onpremiseexamples.py +++ b/device-detection/fiftyone_devicedetection_examples/tests/test_onpremiseexamples.py @@ -21,6 +21,8 @@ # ********************************************************************* import os +import shutil +import tempfile import unittest from fiftyone_pipeline_core.logger import Logger from fiftyone_devicedetection_examples.example_utils import ExampleUtils @@ -30,11 +32,23 @@ from fiftyone_devicedetection_examples.onpremise.match_metrics import MatchMetricsConsole from fiftyone_devicedetection_examples.onpremise.datafileupdate_console import DataFileUpdateConsole +from .data_update_standin import newer_copy, read_published, serving from .live_cloud import is_set # Set to run the performance tests. RUN_PERFORMANCE_TESTS = "_51DEGREES_RUN_PERFORMANCE_TESTS" +# The fetched data file the update example updates. +TAC_DATAFILE_NAME = "TAC-HashV41.hash" + +# The products the stand-in's licence key holds, the second being the +# product of the TAC data file. +STAND_IN_PRODUCTS = ("V4Enterprise", "V4TAC") + +# A made-up licence key, which is all the stand-in needs, so the tests never +# use a real one. +MADE_UP_LICENSE_KEY = "MADE-UP-LICENCE-KEY-FOR-THE-STAND-IN" + class DeviceDetectionExampleTests(unittest.TestCase): # Init method - Set data file for hash examples and the evidence file @@ -59,12 +73,39 @@ def test_onpremise_match_metrics(self): example = MatchMetricsConsole() example.run(self.data_file, False, self.logger, print) - def test_onpremise_datafileupdate_console(self): - example = DataFileUpdateConsole() - license_key = ExampleUtils.get_license_key() - # The license key the tests run with holds the TAC data file, whose - # product is V4TAC, so that is the file and the product asked for. - example.run("TAC-HashV41.hash", license_key, False, self.logger, print, "V4TAC") + def update_from_stand_in(self, product): + """Runs the data file update example against the stand-in, which + serves a copy of the fetched TAC data file published tomorrow. Gives the requests the stand-in received, the published + date of the file the example updated, and the date it should hold.""" + source = ExampleUtils.find_file(TAC_DATAFILE_NAME) + self.assertIsNotNone( + source, f"{TAC_DATAFILE_NAME} is missing. CI's fetch-assets " + "script puts it in place.") + with tempfile.TemporaryDirectory() as folder: + target = os.path.join(folder, TAC_DATAFILE_NAME) + shutil.copyfile(source, target) + served = os.path.join(folder, "served.hash") + expected = newer_copy(source, served) + with serving(STAND_IN_PRODUCTS, served) as stand_in: + DataFileUpdateConsole().run( + target, MADE_UP_LICENSE_KEY, False, self.logger, print, + product) + return stand_in.requests, read_published(target), expected + + def test_onpremise_datafileupdate_console_with_product(self): + # The product given is the one asked for, from the first request. + requests, published, expected = self.update_from_stand_in("V4TAC") + self.assertEqual(("V4TAC", 200), requests[0], requests) + self.assertEqual(expected, published) + + def test_onpremise_datafileupdate_console_without_product(self): + # With no product given, the first request names none and gets the + # list of products, and the second asks for the product of the data + # file in use. + requests, published, expected = self.update_from_stand_in(None) + self.assertEqual((None, 300), requests[0], requests) + self.assertEqual(("V4TAC", 200), requests[1], requests) + self.assertEqual(expected, published) def test_onpremise_datafileupdate_programmatic(self): # The update the example asks for itself, which needs no licence diff --git a/device-detection/fiftyone_devicedetection_examples/tox.ini b/device-detection/fiftyone_devicedetection_examples/tox.ini index c601a295..70ad0826 100644 --- a/device-detection/fiftyone_devicedetection_examples/tox.ini +++ b/device-detection/fiftyone_devicedetection_examples/tox.ini @@ -43,6 +43,12 @@ pass_env = # The marker selection of ../ci/run-integration-tests.ps1, which leaves # the live tests out when no resource key is passed. PYTEST_ADDOPTS +set_env = + # No test here uses a real licence key. The data file update tests give + # the example a made-up key and a stand-in for the Distributor, and the + # others run as a fresh clone does, with no key. So the key is passed + # empty, whatever the environment holds. + _51DEGREES_LICENSE_KEY = [testenv:pre-publish] deps =