From 5721df350af73b2c6f2d5f82b464ffea20a9abb9 Mon Sep 17 00:00:00 2001 From: Raman Marozau Date: Thu, 26 Nov 2026 02:28:43 +0300 Subject: [PATCH 1/3] v1.1.6 --- .github/docs/README.md | 68 +++++++--------- .github/docs/deploy-docs.sh | 50 ++++++------ .github/docs/prepare-server.sh | 34 ++++++++ .github/docs/ssh.sh | 28 +++++++ .github/docs/test-deploy.sh | 27 +++++-- .github/workflows/docs.yml | 59 +++++++------- .github/workflows/prepare-docs.yml | 46 +++++++++++ .github/workflows/publish.yml | 28 ++++--- .github/workflows/security.yml | 4 +- .github/workflows/tested-revision.yml | 78 +++++++++++++++++++ CHANGELOG.md | 16 +++- README.md | 9 ++- django_gc/api.py | 10 +-- django_gc/services/cache.py | 11 +++ django_gc/services/global_config_service.py | 26 ++++--- docs/content/api-reference.md | 6 +- docs/content/cache.md | 5 +- docs/content/contrib.md | 2 +- docs/content/getting-started.md | 6 +- docs/content/how-it-works.md | 6 +- docs/content/intro.md | 4 +- docs/content/operations.md | 6 +- docs/content/settings-and-checks.md | 4 +- .../current/api-reference.md | 6 +- .../current/cache.md | 5 +- .../current/contrib.md | 2 +- .../current/getting-started.md | 6 +- .../current/how-it-works.md | 6 +- .../current/intro.md | 4 +- .../current/operations.md | 6 +- .../current/settings-and-checks.md | 4 +- pyproject.toml | 4 +- tests/fakes.py | 2 + tests/test_database_reads.py | 57 ++++++++++++++ tests/test_global_config_signals.py | 14 ++-- tests/test_key_names.py | 3 + tests/test_task.py | 4 + uv.lock | 2 +- 38 files changed, 494 insertions(+), 164 deletions(-) create mode 100644 .github/docs/prepare-server.sh create mode 100644 .github/docs/ssh.sh create mode 100644 .github/workflows/prepare-docs.yml create mode 100644 .github/workflows/tested-revision.yml create mode 100644 tests/test_database_reads.py diff --git a/.github/docs/README.md b/.github/docs/README.md index 2a7e645..cffabf5 100644 --- a/.github/docs/README.md +++ b/.github/docs/README.md @@ -16,10 +16,10 @@ The server builds the Dockerfile from the selected revision. Both documentation deployment and PyPI publishing require security and test checks for the exact revision. The separate **Security checks** workflow runs Gitleaks, Python and Django SAST and dependency checks, JavaScript and TypeScript SAST and npm -audit, then checks GitHub Actions. The shared CI then runs the Python checks -and matrix one job at a time, builds the wheel and sdist, and type-checks -and builds both documentation locales. A failing check stops publishing. Check -the **Documentation** run for the deployment result. +audit, then checks GitHub Actions. The verification job checks the result of +the existing `testing.yml` run on `main` for that SHA after scanning. +Publish the current head of `main` after its tests succeed. Check the +**Documentation** run for the deployment result. ### PyPI Trusted Publishing @@ -49,7 +49,7 @@ Add `DOCS_PORT` as an **Environment variable**. | `DOCS_PORT` | Free loopback port for this documentation site, for example `18080` | Assign each documentation site on the host its own `DOCS_PORT`. -Set `SSH_USER` to `docs-deploy`. For `SSH_HOST_KEY`, use the first two +Set `SSH_USER` to the existing deployment account, for example `deploy`. For `SSH_HOST_KEY`, use the first two fields of the server's `/etc/ssh/ssh_host_ed25519_key.pub`, for example `ssh-ed25519 AAAA…`. Obtain the key through the server console or its administrator. From the server console, print the two fields with: @@ -70,39 +70,31 @@ ssh-keygen -t ed25519 -f ./gc-docs-ci -C django-gc-docs-ci gh secret set SSH_PRIVATE_KEY --env docs-production --repo RDDLab/Django-GlobalConfig < ./gc-docs-ci ``` -### Server setup - -1. Create the unprivileged `docs-deploy` account with a home directory, - a shell for OpenSSH's forced command, and its own rootless Docker - daemon with Docker Compose V2. Enable the rootless Docker user service - and lingering so the daemon remains available without a login session. - Install Git, Bash, tar, and flock. Configure outbound access to GitHub, - the npm registry, and the container registries. For a private Git - repository, configure read-only Git HTTPS credentials for this account. -2. From a reviewed revision, install the deployment script and Compose - file as root-owned files. The CI key can invoke only this installed - script. - - ```sh - sudo install -m 0755 .github/docs/deploy-docs.sh /usr/local/bin/django-gc-docs-deploy - sudo install -d -m 0755 /usr/local/share/django-gc-docs - sudo install -m 0644 .github/docs/compose.yml /usr/local/share/django-gc-docs/compose.yml - ``` - -3. In the account's `.ssh/authorized_keys`, prepend - `restrict,command="/usr/local/bin/django-gc-docs-deploy"` to the - dedicated public key. Set `.ssh` to mode 0700 and `authorized_keys` - to 0600, both owned by `docs-deploy`. The GitHub Actions runner must - be able to reach the configured SSH port. -4. Point the existing HTTPS reverse proxy for - `django-gc.rdd-lab.com` at `127.0.0.1:`. When you - change this setting, update the proxy upstream to match. - -Install both server files before the first deployment. -The workflow sends the commit SHA and host port to the forced SSH command. -The server validates both, fetches `main` from GitHub and checks that the -commit belongs to it. Rootless Docker builds and serves the site. Angie -and the container health check use its internal port `8080`. +### Server preparation and deployment + +Use an existing unprivileged account that can execute commands over SSH and +access Docker with Compose V2. Bash, tar, and flock must be available on the host. +The existing GitHub Actions key can use the `restrict` option in +`~/.ssh/authorized_keys`. Use a key that can execute the workflow's SSH +commands. For a key previously configured with `command=`, use a dedicated +key without that option for both preparation and deployment. + +After the checks succeed, `docs.yml` calls `prepare-docs.yml` using the +same `docs-production` secrets. It sends the deployment script and +Compose file over SSH and installs both together under +`$HOME/.local/share/django-gc-docs//`. Repeating the +preparation for the same revision reuses the installed files. To prepare +the server by itself, run **Prepare documentation server** from `main`. + +The deploy job sends a source archive for the selected commit from its GitHub +checkout. The SSH account builds and updates the container with its Docker +context or socket. When a rootless socket is available and no custom Docker +context is selected, the script uses that socket. Both jobs run with the +existing account's permissions. + +Point the HTTPS reverse proxy for `django-gc.rdd-lab.com` at +`127.0.0.1:`. Angie and the container health check use the +container's internal port `8080`. The deployment lock serializes updates. The container checks both `/` and `/ru/`. If the new deployment fails, the script restores the previous diff --git a/.github/docs/deploy-docs.sh b/.github/docs/deploy-docs.sh index 8cb3e16..65c546a 100644 --- a/.github/docs/deploy-docs.sh +++ b/.github/docs/deploy-docs.sh @@ -2,37 +2,29 @@ set -euo pipefail umask 077 -if [[ ! "${SSH_ORIGINAL_COMMAND:-}" =~ ^([0-9a-f]{40})[[:blank:]]([1-9][0-9]{0,4})$ ]] || - (( BASH_REMATCH[2] > 65535 )); then - echo 'Expected a full commit SHA and a host port from 1 to 65535 as the SSH command.' >&2 +if (( $# != 2 )) || [[ ! "$1" =~ ^[0-9a-f]{40}$ || ! "$2" =~ ^[1-9][0-9]{0,4}$ ]] || + (( $2 > 65535 )); then + echo 'Expected a full commit SHA and a host port from 1 to 65535.' >&2 exit 1 fi -sha=${BASH_REMATCH[1]} -export DOCS_PORT="${BASH_REMATCH[2]}" +sha=$1 +export DOCS_PORT=$2 state_dir="$HOME/.local/state/django-gc-docs" -repo="$state_dir/repository.git" -compose_file=/usr/local/share/django-gc-docs/compose.yml +deploy_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +compose_file="$deploy_dir/compose.yml" -# Use the dedicated rootless daemon even when SSH has no login session. -DOCKER_HOST="unix:///run/user/$(id -u)/docker.sock" -export DOCKER_HOST -unset DOCKER_CONTEXT +# Use a rootless socket when SSH did not start a session and Docker has no custom context. +docker_socket="/run/user/$(id -u)/docker.sock" +if [[ -z "${DOCKER_HOST:-}" && -z "${DOCKER_CONTEXT:-}" && -S "$docker_socket" ]] && + [[ "$(docker context show)" == default ]]; then + export DOCKER_HOST="unix://$docker_socket" +fi mkdir -p "$state_dir" exec 9>"$state_dir/deploy.lock" flock -w 300 9 -if [[ ! -d "$repo/objects" ]]; then - git init --bare "$repo" -fi -git --git-dir="$repo" fetch --no-tags https://github.com/RDDLab/Django-GlobalConfig.git \ - '+refs/heads/main:refs/heads/main' -if ! git --git-dir="$repo" merge-base --is-ancestor "$sha" refs/heads/main; then - echo 'The documentation revision must be a commit in main.' >&2 - exit 1 -fi - compose() { docker compose --project-name django-gc-docs --env-file /dev/null --file "$compose_file" "$@" } @@ -67,8 +59,18 @@ trap 'exit 129' HUP trap 'exit 130' INT trap 'exit 143' TERM -git --git-dir="$repo" archive "$sha" docs .github/docs | tar -x -C "$release_dir" -dockerfile="$release_dir/.github/docs/Dockerfile" +tar -xf - -C "$release_dir" +if [[ -f "$release_dir/.github/docs/Dockerfile" ]]; then + build_context="$release_dir" + dockerfile="$build_context/.github/docs/Dockerfile" +else + build_context="$release_dir/docs" + dockerfile="$build_context/Dockerfile" +fi +if [[ ! -f "$dockerfile" ]]; then + echo 'The documentation archive does not contain a Dockerfile.' >&2 + exit 1 +fi export DOCS_IMAGE=django-gc-docs:"$sha" previous_container=$(compose ps --all --quiet docs) if [[ -n "$previous_container" ]]; then @@ -80,7 +82,7 @@ if [[ -n "$previous_container" ]]; then fi fi -docker build --file "$dockerfile" --tag "$DOCS_IMAGE" "$release_dir" +docker build --file "$dockerfile" --tag "$DOCS_IMAGE" "$build_context" new_image=$(docker image inspect --format '{{.Id}}' "$DOCS_IMAGE") restore_service=true compose up --detach --wait --wait-timeout 60 diff --git a/.github/docs/prepare-server.sh b/.github/docs/prepare-server.sh new file mode 100644 index 0000000..b6899eb --- /dev/null +++ b/.github/docs/prepare-server.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -euo pipefail +umask 077 + +if (( $# != 1 )) || [[ ! "$1" =~ ^[0-9a-f]{40}$ ]]; then + echo 'Expected a full workflow commit SHA.' >&2 + exit 1 +fi + +source_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +base_dir="$HOME/.local/share/django-gc-docs" +install_dir="$base_dir/$1" + +mkdir -p -- "$base_dir" +staging_dir=$(mktemp -d "$base_dir/.prepare.XXXXXXXX") +trap 'rm -rf -- "$staging_dir"' EXIT + +bash -n "$source_dir/deploy-docs.sh" +install -m 0700 "$source_dir/deploy-docs.sh" "$staging_dir/deploy-docs.sh" +install -m 0600 "$source_dir/compose.yml" "$staging_dir/compose.yml" + +exec 9>"$base_dir/prepare.lock" +flock -w 60 9 +if [[ -e "$install_dir" ]]; then + if ! cmp -s "$staging_dir/deploy-docs.sh" "$install_dir/deploy-docs.sh" || + ! cmp -s "$staging_dir/compose.yml" "$install_dir/compose.yml"; then + echo 'Prepared deployment files do not match this workflow revision.' >&2 + exit 1 + fi +else + mv -- "$staging_dir" "$install_dir" +fi + +printf 'Prepared documentation deployment files for %s.\n' "$1" diff --git a/.github/docs/ssh.sh b/.github/docs/ssh.sh new file mode 100644 index 0000000..3b7efe9 --- /dev/null +++ b/.github/docs/ssh.sh @@ -0,0 +1,28 @@ +#!/bin/bash +set -euo pipefail + +if [[ ! "${SSH_HOST:-}" =~ ^[[:alnum:].:-]+$ || + ! "${SSH_PORT:-}" =~ ^[1-9][0-9]{0,4}$ ]] || + (( SSH_PORT > 65535 )) || + [[ ! "${SSH_USER:-}" =~ ^[a-z_][a-z0-9_-]*$ || + -z "${SSH_PRIVATE_KEY:-}" || ! "${SSH_HOST_KEY:-}" =~ ^ssh-ed25519[[:blank:]]+[A-Za-z0-9+/]+=*$ ]]; then + echo 'Invalid or missing docs-production SSH settings.' >&2 + exit 1 +fi + +umask 077 +ssh_dir=$(mktemp -d) +trap 'rm -rf -- "$ssh_dir"' EXIT +printf '%s\n' "$SSH_PRIVATE_KEY" > "$ssh_dir/key" +known_host=$SSH_HOST +if (( SSH_PORT != 22 )); then + known_host="[$SSH_HOST]:$SSH_PORT" +fi +printf '%s %s\n' "$known_host" "$SSH_HOST_KEY" > "$ssh_dir/known_hosts" +unset SSH_PRIVATE_KEY + +ssh -F /dev/null -T -p "$SSH_PORT" -l "$SSH_USER" -i "$ssh_dir/key" \ + -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes \ + -o "UserKnownHostsFile=$ssh_dir/known_hosts" -o GlobalKnownHostsFile=/dev/null \ + -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \ + -- "$SSH_HOST" "$@" diff --git a/.github/docs/test-deploy.sh b/.github/docs/test-deploy.sh index e3dcf61..7de01f5 100644 --- a/.github/docs/test-deploy.sh +++ b/.github/docs/test-deploy.sh @@ -3,14 +3,29 @@ set -euo pipefail docs_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) sha=0123456789abcdef0123456789abcdef01234567 -expected='Expected a full commit SHA and a host port from 1 to 65535 as the SSH command.' -for invalid in "$sha" "$sha 0" "$sha 65536" "$sha 18080 extra"; do - if output=$(SSH_ORIGINAL_COMMAND="$invalid" bash "$docs_dir/deploy-docs.sh" 2>&1) || - [[ "$output" != "$expected" ]]; then - echo 'The deployment script accepted an invalid SSH command.' >&2 +expected='Expected a full commit SHA and a host port from 1 to 65535.' +reject_deploy_arguments() { + local output + if output=$(bash "$docs_dir/deploy-docs.sh" "$@" 2>&1) || [[ "$output" != "$expected" ]]; then + echo 'The deployment script accepted invalid arguments.' >&2 exit 1 fi -done +} +reject_deploy_arguments "$sha" +reject_deploy_arguments bad-sha 18080 +reject_deploy_arguments "$sha" 0 +reject_deploy_arguments "$sha" 65536 +reject_deploy_arguments "$sha" 18080 extra + +if command -v flock >/dev/null; then + test_home=$(mktemp -d) + trap 'rm -rf -- "$test_home"' EXIT + HOME="$test_home" bash "$docs_dir/prepare-server.sh" "$sha" + HOME="$test_home" bash "$docs_dir/prepare-server.sh" "$sha" + prepared="$test_home/.local/share/django-gc-docs/$sha" + cmp -s "$docs_dir/deploy-docs.sh" "$prepared/deploy-docs.sh" + cmp -s "$docs_dir/compose.yml" "$prepared/compose.yml" +fi export DOCS_IMAGE=django-gc-docs:test compose_config() { diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 2d9d2db..db341b0 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -45,23 +45,39 @@ jobs: source_sha: ${{ needs.revision.outputs.source_sha }} checks: - name: Verify deployment revision + name: Verify successful tests for deployment revision needs: [revision, security] - uses: ./.github/workflows/testing.yml + permissions: + actions: read + contents: read + uses: ./.github/workflows/tested-revision.yml with: source_sha: ${{ needs.revision.outputs.source_sha }} + prepare: + name: Prepare documentation server + needs: checks + uses: ./.github/workflows/prepare-docs.yml + deploy: name: Deploy documentation over SSH - needs: [revision, checks] + needs: [revision, prepare] runs-on: ubuntu-latest timeout-minutes: 30 environment: name: docs-production url: https://django-gc.rdd-lab.com/ - permissions: {} + permissions: + contents: read steps: - - name: Request server-side build and deployment + - uses: actions/checkout@3d3c42e5aac5ba805da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Send documentation source and deploy + shell: bash env: SOURCE_SHA: ${{ needs.revision.outputs.source_sha }} SSH_HOST: ${{ secrets.SSH_HOST }} @@ -71,35 +87,20 @@ jobs: SSH_HOST_KEY: ${{ secrets.SSH_HOST_KEY }} DOCS_PORT: ${{ vars.DOCS_PORT }} run: | - if [[ ! "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ || - ! "$SSH_HOST" =~ ^[[:alnum:].:-]+$ || - ! "$SSH_PORT" =~ ^[1-9][0-9]{0,4}$ ]] || - (( SSH_PORT > 65535 )) || - [[ ! "$SSH_USER" =~ ^[a-z_][a-z0-9_-]*$ || - -z "$SSH_PRIVATE_KEY" || ! "$SSH_HOST_KEY" =~ ^ssh-ed25519[[:blank:]]+[A-Za-z0-9+/]+=*$ ]]; then - echo "::error::Invalid or missing docs-production SSH settings." + if [[ ! "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ || ! "$GITHUB_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Full source and workflow commit SHAs are required." exit 1 fi - if [[ ! "$DOCS_PORT" =~ ^[1-9][0-9]{0,4}$ ]] || (( DOCS_PORT > 65535 )); then - echo "::error::Set the docs-production variable DOCS_PORT to a free host port from 1 to 65535." + echo "::error::Set DOCS_PORT to a free host port from 1 to 65535." exit 1 fi - umask 077 - ssh_dir=$(mktemp -d) - trap 'rm -rf -- "$ssh_dir"' EXIT - printf '%s\n' "$SSH_PRIVATE_KEY" > "$ssh_dir/key" - known_host=$SSH_HOST - if (( SSH_PORT != 22 )); then - known_host="[$SSH_HOST]:$SSH_PORT" + source_paths=(docs) + if git cat-file -e "$SOURCE_SHA:.github/docs/Dockerfile" 2>/dev/null; then + source_paths+=(.github/docs) fi - printf '%s %s\n' "$known_host" "$SSH_HOST_KEY" > "$ssh_dir/known_hosts" - unset SSH_PRIVATE_KEY - ssh -F /dev/null -nT -p "$SSH_PORT" -l "$SSH_USER" -i "$ssh_dir/key" \ - -o BatchMode=yes -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes \ - -o "UserKnownHostsFile=$ssh_dir/known_hosts" -o GlobalKnownHostsFile=/dev/null \ - -o ConnectTimeout=15 \ - -o ServerAliveInterval=15 -o ServerAliveCountMax=3 \ - -- "$SSH_HOST" "$SOURCE_SHA $DOCS_PORT" + git archive "$SOURCE_SHA" "${source_paths[@]}" | + bash .github/docs/ssh.sh \ + "bash \"\$HOME/.local/share/django-gc-docs/$GITHUB_SHA/deploy-docs.sh\" $SOURCE_SHA $DOCS_PORT" diff --git a/.github/workflows/prepare-docs.yml b/.github/workflows/prepare-docs.yml new file mode 100644 index 0000000..78ba170 --- /dev/null +++ b/.github/workflows/prepare-docs.yml @@ -0,0 +1,46 @@ +name: Prepare documentation server + +on: + workflow_call: + workflow_dispatch: + +permissions: + contents: read + +jobs: + prepare: + name: Install documentation deployment files as the SSH user + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + timeout-minutes: 5 + environment: docs-production + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + + - name: Prepare server files + shell: bash + env: + SSH_HOST: ${{ secrets.SSH_HOST }} + SSH_PORT: ${{ secrets.SSH_PORT }} + SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }} + SSH_USER: ${{ secrets.SSH_USER }} + SSH_HOST_KEY: ${{ secrets.SSH_HOST_KEY }} + run: | + if [[ ! "$GITHUB_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::A full workflow commit SHA is required." + exit 1 + fi + + remote_command=$(cat <<'SH' + set -eu + upload_dir=$(mktemp -d) + trap 'rm -rf -- "$upload_dir"' EXIT + tar -xf - -C "$upload_dir" -- prepare-server.sh deploy-docs.sh compose.yml + bash "$upload_dir/prepare-server.sh" "$DOCS_WORKFLOW_SHA" + SH + ) + tar -C .github/docs -cf - prepare-server.sh deploy-docs.sh compose.yml | + bash .github/docs/ssh.sh "export DOCS_WORKFLOW_SHA=$GITHUB_SHA; $remote_command" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index e480703..3396db6 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -16,11 +16,15 @@ jobs: source_sha: ${{ github.sha }} checks: - name: Verify package revision + name: Verify successful tests for main HEAD needs: security - uses: ./.github/workflows/testing.yml + permissions: + actions: read + contents: read + uses: ./.github/workflows/tested-revision.yml with: source_sha: ${{ github.sha }} + require_main_head: true release-build: needs: checks @@ -30,16 +34,9 @@ jobs: steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 + ref: ${{ github.sha }} persist-credentials: false - - name: Require release revision from main - run: | - if ! git merge-base --is-ancestor HEAD origin/main; then - echo "::error::The package revision must be a commit in main." - exit 1 - fi - - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 with: version: "0.13.10" @@ -63,6 +60,7 @@ jobs: needs: release-build timeout-minutes: 10 permissions: + contents: read id-token: write environment: @@ -76,6 +74,16 @@ jobs: name: release-dists path: dist/ + - name: Confirm the package revision is still main HEAD + env: + GH_TOKEN: ${{ github.token }} + run: | + main_sha=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha') + if [[ "$GITHUB_SHA" != "$main_sha" ]]; then + echo "::error::Main advanced before publishing. Publish the new tested head of main." + exit 1 + fi + - name: Publish to PyPI uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index 8528345..b5753e2 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -118,8 +118,8 @@ jobs: ACTIONLINT_VERSION: v1.7.12 run: | go run "github.com/rhysd/actionlint/cmd/actionlint@$ACTIONLINT_VERSION" - for script in .github/docs/deploy-docs.sh .github/docs/test-deploy.sh .github/scripts/compile-translations.sh; do + for script in .github/docs/*.sh .github/scripts/compile-translations.sh; do bash -n "$script" done - shellcheck .github/docs/deploy-docs.sh .github/docs/test-deploy.sh .github/scripts/compile-translations.sh + shellcheck .github/docs/*.sh .github/scripts/compile-translations.sh bash .github/docs/test-deploy.sh diff --git a/.github/workflows/tested-revision.yml b/.github/workflows/tested-revision.yml new file mode 100644 index 0000000..8aa8fbc --- /dev/null +++ b/.github/workflows/tested-revision.yml @@ -0,0 +1,78 @@ +name: Verify tested revision + +on: + workflow_call: + inputs: + source_sha: + description: Commit to verify against the testing workflow on main + required: true + type: string + require_main_head: + description: Require the selected commit to still be the head of main + type: boolean + default: false + +permissions: + actions: read + contents: read + +jobs: + verify: + name: Check completed tests on main + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Verify test results for the selected SHA + shell: bash + env: + GH_TOKEN: ${{ github.token }} + SOURCE_SHA: ${{ inputs.source_sha }} + REQUIRE_MAIN_HEAD: ${{ inputs.require_main_head }} + run: | + if [[ ! "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::A full commit SHA is required." + exit 1 + fi + + if [[ "$REQUIRE_MAIN_HEAD" == true ]]; then + if [[ "$GITHUB_EVENT_NAME" == workflow_dispatch && "$GITHUB_REF" != refs/heads/main ]]; then + echo "::error::Run manual publishing from main." + exit 1 + fi + main_sha=$(gh api "repos/$GITHUB_REPOSITORY/git/ref/heads/main" --jq '.object.sha') + if [[ "$SOURCE_SHA" != "$main_sha" ]]; then + echo "::error::The package revision must be the current head of main." + exit 1 + fi + fi + + runs=$(gh api --paginate --method GET "repos/$GITHUB_REPOSITORY/actions/workflows/testing.yml/runs" \ + -f branch=main -f head_sha="$SOURCE_SHA" -F per_page=100) + run=$(jq -cs --arg sha "$SOURCE_SHA" ' + [.[] | .workflow_runs[] | select( + .head_branch == "main" and .head_sha == $sha and (.event == "push" or .event == "workflow_dispatch") + )] | sort_by(.created_at, .id) | last // empty + ' <<< "$runs") + if [[ -z "$run" ]]; then + echo "::error::No testing.yml run on main was found for $SOURCE_SHA." + exit 1 + fi + + run_url=$(jq -r '.html_url' <<< "$run") + if ! jq -e '.status == "completed" and .conclusion == "success"' <<< "$run" > /dev/null; then + echo "::error::The latest testing.yml run for $SOURCE_SHA has not succeeded. $run_url" + exit 1 + fi + + run_id=$(jq -r '.id' <<< "$run") + jobs=$(gh api --paginate --method GET "repos/$GITHUB_REPOSITORY/actions/runs/$run_id/jobs" \ + -f filter=all -F per_page=100) + if ! jq -es ' + [.[] | .jobs[] | select(.name | startswith("Pytest (Python "))] + | group_by(.name) | map(max_by(.id)) + | length > 0 and all(.[]; .conclusion == "success") + ' <<< "$jobs" > /dev/null; then + echo "::error::No successful Pytest matrix for $SOURCE_SHA. $run_url" + exit 1 + fi + echo "Verified testing.yml for $SOURCE_SHA: $run_url" diff --git a/CHANGELOG.md b/CHANGELOG.md index b639d82..f3597ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to **Django-GC** are documented in this file. ## [Unreleased] +## [1.1.6] — 2026-11-26 + +### Fixed + +- Read settings directly from the database with Django's local-memory or dummy cache. + Snapshot refreshes are skipped in this mode so each worker reads current values. + +### Changed + +- Scan the release revision, then verify that it is the current head of `main` and that + its latest test workflow succeeded. Release and documentation deployment reuse + existing test results. + ## [1.1.5] — 2026-11-26 ### Added @@ -89,5 +102,6 @@ All notable changes to **Django-GC** are documented in this file. [1.0.2]: https://github.com/RDDLab/Django-GlobalConfig/releases/tag/1.0.2 [1.0.1]: https://github.com/RDDLab/Django-GlobalConfig/releases/tag/1.0.1 -[Unreleased]: https://github.com/RDDLab/Django-GlobalConfig/compare/1.1.5...HEAD +[Unreleased]: https://github.com/RDDLab/Django-GlobalConfig/compare/1.1.6...HEAD +[1.1.6]: https://github.com/RDDLab/Django-GlobalConfig/compare/1.1.5...1.1.6 [1.1.5]: https://github.com/RDDLab/Django-GlobalConfig/compare/1.1.4...1.1.5 diff --git a/README.md b/README.md index 389d39f..d7a4eb6 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![Logo](https://github.com/RDDLab/Django-GlobalConfig/raw/main/docs/static/img/logo.svg) [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=for-the-badge)](https://opensource.org/licenses/MIT) -[![Version: 1.1.5](https://img.shields.io/badge/version-1.1.5-blue.svg?style=for-the-badge)](https://github.com/RDDLab/Django-GlobalConfig/releases/tag/1.1.5) +[![Version: 1.1.6](https://img.shields.io/badge/version-1.1.6-blue.svg?style=for-the-badge)](https://github.com/RDDLab/Django-GlobalConfig/releases/tag/1.1.6) [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json&style=for-the-badge)](https://docs.astral.sh/ruff) [![pyrefly](https://img.shields.io/endpoint?url=https://pyrefly.org/badge.json&style=for-the-badge)](https://pyrefly.org) [![PyPI](https://img.shields.io/pypi/v/django-gc?style=for-the-badge)](https://pypi.org/project/django-gc/) @@ -26,14 +26,15 @@ # Django-GC -Django-GC stores typed runtime settings in the database and serves them from Django's cache. Application code never reads a value through the ORM. The project owns the keys; this package is the mechanism. +Django-GC stores typed runtime settings in the database and uses a shared cache when configured. Application code never reads a value through the ORM. The project owns the keys; this package is the mechanism. ## Features - **Code-declared keys** — categories and definitions live in Django settings and are synchronized by `initialize_global_configs`. - **Typed values** — strings, numbers, dates, arrays, choices, JSON, UUID, and optional secure secrets. - **Targeted cache updates** — saving one setting refreshes only its typed cache entry. -- **Full recovery snapshot** — `get_value()` never falls back to a single-row ORM read on cache miss. +- **Full recovery snapshot** — a miss in a shared cache rebuilds the snapshot. +- **Direct database reads** — local-memory and dummy caches use current values from the database. - **Stock Django Admin** — edit values with standard `ModelAdmin` and Django's built-in change history. - **Optional Celery** — periodic full snapshot refresh. - **Fully typed** — ships `py.typed`; compatible with pyrefly and standard type checkers. @@ -48,7 +49,7 @@ Django-GC stores typed runtime settings in the database and serves them from Dja ## Installation ```bash -pip install 'django-gc>=1.1.5' +pip install 'django-gc>=1.1.6' ``` ```python diff --git a/django_gc/api.py b/django_gc/api.py index 2c476dd..37c2d63 100644 --- a/django_gc/api.py +++ b/django_gc/api.py @@ -9,8 +9,8 @@ def get_value(key: str | StrEnum, *, use_cache: bool = True) -> Any: """ Return the typed value of a setting identified by its current key or a declared alias. - The default cache-backed read refreshes the snapshot on a miss. Pass use_cache=False to read the row - directly. A missing setting or an invalid stored value raises a GlobalConfigError subclass. + Use a shared cache by default and refresh its snapshot on a miss. Read the database directly when a local + or dummy backend is configured or use_cache is False. Missing or invalid values raise GlobalConfigError. """ from django_gc.services.global_config_service import GlobalConfigService @@ -33,8 +33,8 @@ def refresh_cache() -> int: """ Rebuild the cache snapshot from the declared settings and return the number of entries written. - An incomplete or invalid snapshot raises an error before it can be published. A completed refresh by - another worker can return zero when the wait for the refresh lock times out. + An incomplete or invalid snapshot raises an error before publication. Return zero when a different + worker has already published an acceptable snapshot or when there is no shared cache to refresh. """ from django_gc.services.global_config_service import GlobalConfigService @@ -45,7 +45,7 @@ def is_cache_ready() -> bool: """ Check the cache marker and all typed entries required by the current definitions. - Return a boolean without querying the settings tables. + Return False without a shared cache. This check never queries the settings tables. """ from django_gc.services.global_config_service import GlobalConfigService diff --git a/django_gc/services/cache.py b/django_gc/services/cache.py index 6c1d530..f2eeec3 100644 --- a/django_gc/services/cache.py +++ b/django_gc/services/cache.py @@ -3,6 +3,8 @@ from uuid import uuid4 from django.core.cache import caches +from django.core.cache.backends.dummy import DummyCache +from django.core.cache.backends.locmem import LocMemCache from django_gc.exceptions import GlobalConfigLockNotOwnedError @@ -71,6 +73,15 @@ def __init__(self, alias: str) -> None: """ self._cache = caches[alias] + @property + def is_shared(self) -> bool: + """ + Report whether the configured backend can hold a snapshot shared by workers. + + Disallow process-local and dummy backends. Other backends must be configured for shared access. + """ + return not isinstance(self._cache, (LocMemCache, DummyCache)) + def get(self, key: str, default: Any = None) -> Any: """ Read a cache key or return the supplied default when it is absent. diff --git a/django_gc/services/global_config_service.py b/django_gc/services/global_config_service.py index 085f1b0..6d4321e 100644 --- a/django_gc/services/global_config_service.py +++ b/django_gc/services/global_config_service.py @@ -36,8 +36,7 @@ class GlobalConfigService(Singleton): """ Read and write typed GlobalConfig values and coordinate publication of the cache snapshot. - Runtime reads use the cache by default. The database remains the source of truth for snapshot rebuilds - and explicit fresh reads. + Runtime reads use a shared cache when configured. Process-local and dummy backends use database reads. """ CACHE_KEY_TEMPLATE = 'global-config:{key}' @@ -60,11 +59,11 @@ def get_value(self, key: str | StrEnum, *, use_cache: bool = True) -> Any: """ Return the typed value for a canonical key or a declared alias. - Bypass the cache with use_cache=False. Otherwise, rebuild the snapshot synchronously on a miss and - retry the lookup. Raise GlobalConfigNotFoundError if the setting is still unavailable. + Bypass the cache with use_cache=False or when the backend cannot hold a shared snapshot. + A miss in a shared cache rebuilds the snapshot before retrying the lookup. """ key = resolve_key(key=str(key)) - if not use_cache: + if not use_cache or not self._cache.is_shared: config = GlobalConfig.objects.filter(pk=str(key)).first() if config is None: raise GlobalConfigNotFoundError(key=str(key)) @@ -89,10 +88,10 @@ def get_values(self, *, keys: Sequence[str], use_cache: bool = True) -> dict[str """ Return typed values keyed by the supplied names, including any aliases. - With use_cache=False, fetch all canonical rows in a single query in the caller's database - transaction. Raise GlobalConfigNotFoundError when a requested row is missing. + Fresh reads and backends without shared storage fetch all canonical rows in a single query in the + caller's database transaction. Raise GlobalConfigNotFoundError when a requested row is missing. """ - if use_cache: + if use_cache and self._cache.is_shared: return {key: self.get_value(key=key) for key in keys} canonical_keys = {key: resolve_key(key=key) for key in keys} configs = GlobalConfig.objects.filter(pk__in=canonical_keys.values()) @@ -113,8 +112,10 @@ def refresh_value(self, key: str | StrEnum) -> None: Refresh the cache entry for a single setting under the shared refresh lock. Invalidate the old entry before reading the row and publish the parsed replacement after checking - lock ownership. + lock ownership. Skip the operation when settings are read directly from the database. """ + if not self._cache.is_shared: + return key = resolve_key(key=str(key)) lock = self._cache.get_lock(key=self.REFRESH_LOCK_CACHE_KEY, timeout=self.REFRESH_LOCK_TIMEOUT_SECONDS) acquired = lock.acquire(blocking=True, blocking_timeout=self.REFRESH_LOCK_BLOCKING_TIMEOUT_SECONDS) @@ -146,8 +147,10 @@ def refresh_cache(self, requested_cache_key: str | None = None) -> int: Rebuild the full cache snapshot under the refresh lock and return the number of settings written. When requested_cache_key is supplied, reuse a complete snapshot containing that entry if another - worker publishes it while this call waits. Reusing a snapshot returns zero. + worker publishes it while this call waits. Return zero on reuse or when there is no shared cache. """ + if not self._cache.is_shared: + return 0 lock = self._cache.get_lock(key=self.REFRESH_LOCK_CACHE_KEY, timeout=self.REFRESH_LOCK_TIMEOUT_SECONDS) acquired = lock.acquire(blocking=True, blocking_timeout=self.REFRESH_LOCK_BLOCKING_TIMEOUT_SECONDS) if not acquired: @@ -221,7 +224,10 @@ def is_cache_ready(self) -> bool: Require the readiness marker and a typed cache entry for every active definition. Check the cache and the code-defined catalog without querying the settings tables. + Return False when settings are read directly from the database. """ + if not self._cache.is_shared: + return False marker = self._cache.get(key=self.SNAPSHOT_READY_CACHE_KEY, default=False) if marker is not True: return False diff --git a/docs/content/api-reference.md b/docs/content/api-reference.md index f992a1f..3b96c80 100644 --- a/docs/content/api-reference.md +++ b/docs/content/api-reference.md @@ -25,11 +25,11 @@ You can import the public functions before Django initializes. Call them after D | Function | Returns | Notes | |---|---|---| -| `get_value(key, *, use_cache=True)` | typed value | accepts a `str` or `StrEnum` key, may refresh the snapshot. `use_cache=False` reads the database | +| `get_value(key, *, use_cache=True)` | typed value | accepts a `str` or `StrEnum` key. Reads the database with a local or dummy backend or with `use_cache=False` | | `set_value(key, value)` | `GlobalConfig` | existing keys only; refreshes that cache entry after commit | | `set_typed_value(*, key, value)` | `GlobalConfig` | added in 1.1.5. Validates and serializes a typed value for the declared key | -| `refresh_cache()` | `int` | published key count, or `0` if another owner already published | -| `is_cache_ready()` | `bool` | marker + every declared DTO, no database | +| `refresh_cache()` | `int` | published key count, or `0` when another owner already published or a shared cache is unavailable by configuration | +| `is_cache_ready()` | `bool` | checks the marker and every declared DTO. Returns `False` in database mode | ## Reading and locking multiple settings diff --git a/docs/content/cache.md b/docs/content/cache.md index 37c80a3..826e198 100644 --- a/docs/content/cache.md +++ b/docs/content/cache.md @@ -5,6 +5,9 @@ sidebar_position: 8 + + +Django-GC reads directly from the database with `LocMemCache` or `DummyCache`. Batch reads fetch the requested settings in one query. In this mode `refresh_cache()` and the Celery task return `0`, and `is_cache_ready()` returns `False`. A configured shared backend must be available to read its snapshot. The snapshot lives in Django's cache, alias `GLOBAL_CONFIG_CACHE_ALIAS` (default `default`). @@ -16,7 +19,7 @@ The snapshot lives in Django's cache, alias `GLOBAL_CONFIG_CACHE_ALIAS` (default Lock wait timeout is 35 seconds. If the wait times out, the service accepts an already published snapshot or raises `GlobalConfigRefreshLockTimeoutError`. It never publishes without owning the lock. -Publish uses `cache.set_many`. On Redis/Valkey this is typically one `MSET`. Locmem is enough for tests and a single process. +Publish uses `cache.set_many`. On Redis/Valkey this is typically one `MSET`. After one `GlobalConfig` row is saved and its transaction commits, Django-GC acquires the shared refresh lock, reads that row, and replaces only its typed cache entry. Other entries are not read or changed. Full snapshot publication remains the recovery and reconciliation mechanism for cache misses, initialization, and the optional periodic task. diff --git a/docs/content/contrib.md b/docs/content/contrib.md index 227655b..c61d526 100644 --- a/docs/content/contrib.md +++ b/docs/content/contrib.md @@ -75,7 +75,7 @@ npm run docs:serve Pushes to any branch and pull requests run Security checks. Pushes to protected branches also run the test pipeline. The test pipeline uses the dependency lock, verifies the Django migration state, runs the Python and Django matrix, builds both Python distributions and verifies the English and Russian documentation. The security workflow scans secrets, Python, Django templates, documentation JavaScript and TypeScript, and workflow files. It audits locked Python and npm dependencies. -The release workflow verifies the selected commit before uploading wheel and sdist to PyPI using Trusted Publishing. After upload it dispatches the documentation workflow on `main` for that commit. The documentation workflow rechecks its ancestry and deploys through a dedicated SSH command. The deployment server builds the site with rootless Docker and restores the previous image and port if the new container fails its health check. +The release workflow scans the release revision, verifies it matches the current head of `main` and requires a successful `testing.yml` run for that exact SHA on `main`. Publish only after the test run finishes. Run manual publishing from `main`. After uploading wheel and sdist to PyPI, the workflow dispatches the documentation workflow for the published commit. The documentation workflow checks ancestry and reuses the test result for the selected revision before deploying over SSH. The preparation workflow installs the deployment files in the SSH user’s home directory. The deploy job streams the selected source archive to the server, and the SSH account builds it with Docker. If the container fails its health check, the deployment script restores the previous image and port. [Set up the GitHub environment and the documentation server](https://github.com/RDDLab/Django-GlobalConfig/blob/main/.github/docs/README.md). diff --git a/docs/content/getting-started.md b/docs/content/getting-started.md index 5a439bc..a33e91c 100644 --- a/docs/content/getting-started.md +++ b/docs/content/getting-started.md @@ -10,7 +10,7 @@ This page is the shortest path from an empty Django project to a working Django- ## Installation ```bash -pip install 'django-gc>=1.1.5' +pip install 'django-gc>=1.1.6' ``` ```python @@ -21,7 +21,9 @@ INSTALLED_APPS = [ ] ``` -Use a shared cache in production (Redis, Valkey, or another remote backend). The test suite uses locmem. + + +Configure a shared cache such as Redis or Valkey to serve settings from a snapshot. With Django’s default `LocMemCache` or `DummyCache`, settings are read directly from the database. ## Django settings diff --git a/docs/content/how-it-works.md b/docs/content/how-it-works.md index 79f34b8..bd4ca25 100644 --- a/docs/content/how-it-works.md +++ b/docs/content/how-it-works.md @@ -6,7 +6,9 @@ sidebar_position: 3 -Runtime code reads values only through `get_value()`. ORM reads of a single key, custom cache-aside keys, and domain fallbacks are out of scope for this package. +Runtime code reads settings through `get_value()`. The following flow applies when a shared cache is configured. + + ```mermaid flowchart TD @@ -38,7 +40,7 @@ flowchart TD 8. Publish values and the readiness marker with `set_many` while the lock is still owned. 9. Resolve the requested key. `SECURE` is decrypted only in memory. -There is no single-row database fallback in `get_value()`. Keys have no TTL. A committed save refreshes that key directly; full refresh handles cache-miss recovery and reconciliation. +Without a shared backend (`LocMemCache` or `DummyCache`), `get_value()` reads the requested row directly. Entries in a shared snapshot have no TTL. A committed save refreshes that key directly; full refresh handles cache-miss recovery and reconciliation. ## Refresh triggers diff --git a/docs/content/intro.md b/docs/content/intro.md index 14152f1..7ac32aa 100644 --- a/docs/content/intro.md +++ b/docs/content/intro.md @@ -9,7 +9,7 @@ sidebar_position: 1 ## What Django-GC is -Django-GC stores typed runtime settings in the database and serves them from Django's cache. Application code never reads a value through the ORM. The project owns the keys; this package is the mechanism. +Django-GC stores typed runtime settings in the database and uses a shared cache when configured. Application code never reads a value through the ORM. The project owns the keys; this package is the mechanism. It is not a replacement for `django.conf.settings`. Static deploy-time settings stay in Django settings. This package is for values operators change at runtime: feature flags, limits, secrets that rotate, and similar knobs. @@ -33,7 +33,7 @@ It is not a replacement for `django.conf.settings`. Static deploy-time settings | 3.15 | 6.1.3 | CI runs the full test suite with the locked Django version and the minimum for each Python version. -See the [upgrade and operations guide](./operations.md) for the 1.1.5 deployment sequence. +See the [upgrade and operations guide](./operations.md) for the 1.1.6 upgrade and deployment sequence. Celery is optional and only needed for a periodic refresh task: diff --git a/docs/content/operations.md b/docs/content/operations.md index c6de381..60d5c21 100644 --- a/docs/content/operations.md +++ b/docs/content/operations.md @@ -4,6 +4,10 @@ title: Upgrade and operations +## Upgrade from 1.1.5 + +Version 1.1.6 adds no migrations. `LocMemCache` and `DummyCache` now use database reads. Deploy workers together so process-local snapshots from the previous version stop serving reads. + ## Upgrade from 1.1.4 1. Apply the schema migrations. @@ -23,7 +27,7 @@ If an integrating app has system checks that require initialized keys, use `pyth ## Share and verify the snapshot -Use a shared cache such as Redis or Valkey for web processes and workers. Select the alias with `GLOBAL_CONFIG_CACHE_ALIAS` and isolate deployments with Django's `KEY_PREFIX`. Define `GLOBAL_CONFIG_ENCRYPTION_KEY` through the deployment secret store before using `SECURE` settings. +For snapshot mode, use a shared cache such as Redis or Valkey for web processes and workers. Select the alias with `GLOBAL_CONFIG_CACHE_ALIAS` and isolate deployments with Django's `KEY_PREFIX`. Define `GLOBAL_CONFIG_ENCRYPTION_KEY` through the deployment secret store before using `SECURE` settings. ```python from django_gc import is_cache_ready, refresh_cache diff --git a/docs/content/settings-and-checks.md b/docs/content/settings-and-checks.md index 162011d..341efc4 100644 --- a/docs/content/settings-and-checks.md +++ b/docs/content/settings-and-checks.md @@ -34,4 +34,6 @@ from django_gc.tasks import refresh_global_configs_cache Keep keys in a project `StrEnum` and pass that member to `get_value()` and `set_value()`. Do not scatter raw key strings at call sites. -Use a shared cache backend in multi-process deployments. Locmem does not share a snapshot across workers. + + +Use a cache backend shared by all workers and web processes to serve a snapshot. With `LocMemCache` or `DummyCache`, reads go to the database and the Celery refresh task returns `0`. diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/api-reference.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/api-reference.md index 092bb36..2291aa7 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/api-reference.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/api-reference.md @@ -25,11 +25,11 @@ from django_gc import ( | Функция | Возвращает | Заметки | |---|---|---| -| `get_value(key, *, use_cache=True)` | типизированное значение | принимает ключ `str` или `StrEnum`, может обновить снимок. `use_cache=False` читает базу | +| `get_value(key, *, use_cache=True)` | типизированное значение | принимает ключ `str` или `StrEnum`. Читает базу с локальным или dummy-кэшем либо с `use_cache=False` | | `set_value(key, value)` | `GlobalConfig` | только существующие ключи; после commit обновляет этот cache entry | | `set_typed_value(*, key, value)` | `GlobalConfig` | добавлена в 1.1.5. Проверяет и сериализует типизированное значение объявленного ключа | -| `refresh_cache()` | `int` | число опубликованных ключей или `0`, если снимок уже опубликовал другой владелец | -| `is_cache_ready()` | `bool` | маркер + каждый объявленный DTO, без базы | +| `refresh_cache()` | `int` | число опубликованных ключей или `0`, если другой процесс уже опубликовал снимок или общий кэш не настроен | +| `is_cache_ready()` | `bool` | проверяет маркер и каждый объявленный DTO. В режиме чтения из базы возвращает `False` | ## Чтение и блокировка нескольких ключей diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/cache.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/cache.md index 3b9c105..c5c157c 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/cache.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/cache.md @@ -5,6 +5,9 @@ sidebar_position: 8 + + +При `LocMemCache` или `DummyCache` Django-GC читает значения напрямую из базы. Пакетное чтение получает запрошенные настройки одним запросом. В этом режиме `refresh_cache()` и задача Celery возвращают `0`, а `is_cache_ready()` возвращает `False`. Для чтения снимка из настроенного общего кэша этот кэш должен быть доступен. Снимок живёт в Django cache, алиас `GLOBAL_CONFIG_CACHE_ALIAS` (по умолчанию `default`). @@ -16,7 +19,7 @@ sidebar_position: 8 Ожидание lock — 35 секунд. Если timeout, сервис принимает уже опубликованный снимок или бросает `GlobalConfigRefreshLockTimeoutError`. Публикация без владения lock запрещена. -Публикация идёт через `cache.set_many`. На Redis/Valkey это обычно один `MSET`. Locmem достаточно для тестов и одного процесса. +Публикация идёт через `cache.set_many`. На Redis/Valkey это обычно один `MSET`. После сохранения одной строки `GlobalConfig` и commit транзакции Django-GC захватывает общую refresh-блокировку, перечитывает эту строку и заменяет только её типизированный cache entry. Остальные значения не читаются и не меняются. Полный снимок остаётся механизмом восстановления и сверки для cache miss, инициализации и необязательной периодической задачи. diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md index 694d178..ce21b24 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md @@ -99,6 +99,6 @@ npm run docs:serve Push в любую ветку и pull request запускают проверки безопасности. При push в защищённую ветку также запускаются тесты. Тестовый workflow проверяет lock-файл и состояние миграций Django, прогоняет матрицу Python и Django, собирает wheel и sdist, а также проверяет и собирает обе языковые версии документации. Workflow безопасности проверяет секреты, Python, шаблоны Django, JavaScript и TypeScript документации и файлы GitHub Actions. Отдельно выполняется аудит закреплённых зависимостей Python и npm. -Перед выгрузкой пакета в PyPI через Trusted Publishing workflow проверяет выбранный коммит. После выгрузки он запускает деплой документации с этим коммитом на `main`. Workflow документации проверяет принадлежность коммита ветке и вызывает выделенную SSH-команду. Сервер собирает сайт в rootless Docker и восстанавливает прежний образ и порт при ошибке проверки готовности. +Релизный workflow сканирует коммит, сверяет его с текущей вершиной `main` и требует успешный запуск `testing.yml` для этого SHA в `main`. Дождитесь завершения тестов перед публикацией. Ручную публикацию запускайте из `main`. После загрузки wheel и sdist в PyPI запускается деплой документации для опубликованного коммита. Workflow документации проверяет принадлежность коммита ветке и использует результат уже пройденных тестов перед деплоем по SSH. Workflow подготовки устанавливает файлы деплоя в домашний каталог SSH-пользователя. Деплой передаёт на сервер архив выбранного коммита, и SSH-пользователь собирает его через Docker. При ошибке проверки готовности скрипт восстанавливает прежний образ и порт. [Настроить GitHub Environment и сервер документации](https://github.com/RDDLab/Django-GlobalConfig/blob/main/.github/docs/README.md). diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/getting-started.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/getting-started.md index 17e31f6..4b2e832 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/getting-started.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/getting-started.md @@ -10,7 +10,7 @@ sidebar_position: 2 ## Установка ```bash -pip install 'django-gc>=1.1.5' +pip install 'django-gc>=1.1.6' ``` ```python @@ -21,7 +21,9 @@ INSTALLED_APPS = [ ] ``` -В production используйте общий кэш (Redis, Valkey или другой remote backend). Тесты используют locmem. + + +Настройте общий кэш, например Redis или Valkey, чтобы читать настройки из снимка. При `LocMemCache` по умолчанию или `DummyCache` библиотека читает настройки напрямую из базы. ## Django settings diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/how-it-works.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/how-it-works.md index 2f8e45f..b40b18e 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/how-it-works.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/how-it-works.md @@ -6,7 +6,9 @@ sidebar_position: 3 -Runtime-код читает значения только через `get_value()`. ORM-чтение одного ключа, свои cache-aside ключи и доменные fallback в пакет не входят. +Прикладной код читает настройки через `get_value()`. Схема ниже показывает чтение при настроенном общем кэше. + + ```mermaid flowchart TD @@ -38,7 +40,7 @@ flowchart TD 8. Опубликовать значения и маркер готовности через `set_many`, пока lock принадлежит процессу. 9. Вернуть запрошенный ключ. `SECURE` расшифровывается только в памяти. -В `get_value()` нет fallback к чтению одной строки из БД. У ключей нет TTL. После commit сохранённый ключ обновляется точечно; полный refresh отвечает за восстановление после cache miss и периодическую сверку. +При `LocMemCache` или `DummyCache` функция `get_value()` читает нужную строку напрямую из базы. У записей общего снимка нет TTL. После commit сохранённый ключ обновляется точечно; полный refresh отвечает за восстановление после cache miss и периодическую сверку. ## Когда обновляется снимок diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/intro.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/intro.md index 0609a9d..db257f8 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/intro.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/intro.md @@ -9,7 +9,7 @@ sidebar_position: 1 ## Что такое Django-GC -Django-GC хранит типизированные runtime-настройки в базе и отдаёт их из Django cache. Прикладной код не читает значение через ORM. Проект владеет ключами; этот пакет — механизм. +Django-GC хранит типизированные runtime-настройки в базе и использует общий кэш, если он настроен. Прикладной код не читает значение через ORM. Проект владеет ключами; этот пакет — механизм. Это не замена `django.conf.settings`. Статические настройки деплоя остаются в Django settings. Пакет нужен для значений, которые оператор меняет в runtime: флаги, лимиты, ротируемые секреты и похожие ручки. @@ -33,7 +33,7 @@ Django-GC хранит типизированные runtime-настройки | 3.15 | 6.1.3 | CI запускает весь набор тестов на закреплённой и минимальной версиях Django для каждого Python. -[Руководство по обновлению и эксплуатации](./operations.md) описывает порядок перехода на 1.1.5. +[Руководство по обновлению и эксплуатации](./operations.md) описывает порядок перехода на 1.1.6. Celery необязателен и нужен только для периодического refresh: diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/operations.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/operations.md index 0729928..45f9499 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/operations.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/operations.md @@ -4,6 +4,10 @@ title: Обновление и эксплуатация +## Обновление с 1.1.5 + +В 1.1.6 нет новых миграций. При `LocMemCache` и `DummyCache` настройки читаются из базы. Обновите все процессы, чтобы воркеры предыдущей версии перестали читать локальные снимки. + ## Обновление с 1.1.4 1. Примените миграции схемы. @@ -23,7 +27,7 @@ python manage.py check ## Общий снимок кэша -Для веб-процессов и воркеров используйте общий кэш, например Redis или Valkey. Алиас задайте через `GLOBAL_CONFIG_CACHE_ALIAS`, а окружения разделите настройкой Django `KEY_PREFIX`. Перед использованием типа `SECURE` задайте `GLOBAL_CONFIG_ENCRYPTION_KEY` через хранилище секретов окружения. +Для работы со снимком веб-процессам и воркерам нужен общий кэш, например Redis или Valkey. Алиас задайте через `GLOBAL_CONFIG_CACHE_ALIAS`, а окружения разделите настройкой Django `KEY_PREFIX`. Перед использованием типа `SECURE` задайте `GLOBAL_CONFIG_ENCRYPTION_KEY` через хранилище секретов окружения. ```python from django_gc import is_cache_ready, refresh_cache diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/settings-and-checks.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/settings-and-checks.md index a61f018..a5d29ad 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/settings-and-checks.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/settings-and-checks.md @@ -34,4 +34,6 @@ from django_gc.tasks import refresh_global_configs_cache Ключи храните в проектном `StrEnum` и передавайте его в `get_value()` и `set_value()`. Не размазывайте сырые строки ключей по вызовам. -В multi-process деплое используйте общий cache backend. Locmem не разделяет снимок между воркерами. + + +Чтобы использовать снимок, настройте общий кэш для веб-процессов и воркеров. При `LocMemCache` или `DummyCache` библиотека читает настройки из базы, а задача обновления возвращает `0`. diff --git a/pyproject.toml b/pyproject.toml index 69635a8..04d7eb3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,8 +7,8 @@ build-backend = "setuptools.build_meta" [project] name = "django-gc" -version = "1.1.5" -description = "Typed Django runtime configuration stored in the database and served from cache" +version = "1.1.6" +description = "Typed Django runtime configuration with database storage and shared caching" readme = "README.md" authors = [ { name = "Raman Marozau", email = "r.morozov@rdd-lab.com" } diff --git a/tests/fakes.py b/tests/fakes.py index 0638bf1..dc3aab7 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -48,6 +48,8 @@ class FakeCacheBackend: Keep snapshot entries in memory and expose cache operations for deterministic assertions. """ + is_shared = True + def __init__(self, values: dict[str, Any] | None = None, lock: FakeLock | None = None) -> None: self.values: dict[str, Any] = dict(values or {}) self.lock = lock or FakeLock() diff --git a/tests/test_database_reads.py b/tests/test_database_reads.py new file mode 100644 index 0000000..1e534ef --- /dev/null +++ b/tests/test_database_reads.py @@ -0,0 +1,57 @@ +from unittest.mock import patch + +from django.core.cache import cache +from django.test import TestCase, override_settings + +from django_gc import get_value, is_cache_ready, refresh_cache, set_typed_value +from django_gc.dto import GlobalConfigCacheValueDTO +from django_gc.enums import SettingType +from django_gc.services import GlobalConfigService +from django_gc.services.cache import CacheBackend +from django_gc.tasks import refresh_global_configs_cache + +PAGINATION_KEY = 'platform.pagination_size' +SECRET_KEY = 'auth.secret_token' + + +class DatabaseReadsTestCase(TestCase): + """ + Exercise the runtime API when there is no shared cache for settings. + """ + + def test_backends_without_shared_storage_read_current_values(self) -> None: + """ + Bypass both local and dummy backends even if a stale snapshot exists. + + Verify that batch reads need one query and snapshot operations do not access the database. + """ + original = get_value(PAGINATION_KEY, use_cache=False) + service = GlobalConfigService() + for backend_path in ( + 'django.core.cache.backends.locmem.LocMemCache', + 'django.core.cache.backends.dummy.DummyCache' + ): + caches = {'default': {'BACKEND': backend_path, 'LOCATION': 'gc-without-shared-cache'}} + with self.subTest(backend=backend_path), override_settings(CACHES=caches), patch.object( + service, '_cache', CacheBackend(alias='default') + ): + set_typed_value(key=PAGINATION_KEY, value=original) + cache.set(service.build_cache_key(key=PAGINATION_KEY), GlobalConfigCacheValueDTO( + value=999, value_type=SettingType.INTEGER + )) + cache.set(service.SNAPSHOT_READY_CACHE_KEY, True) + + self.assertEqual(get_value(PAGINATION_KEY), original) + set_typed_value(key=PAGINATION_KEY, value=original + 1) + self.assertEqual(get_value(PAGINATION_KEY), original + 1) + + with self.assertNumQueries(1): + self.assertEqual(service.get_values(keys=[PAGINATION_KEY, SECRET_KEY]), { + PAGINATION_KEY: original + 1, + SECRET_KEY: 'secret' + }) + with self.assertNumQueries(0): + self.assertFalse(is_cache_ready()) + self.assertEqual(refresh_cache(), 0) + self.assertEqual(refresh_global_configs_cache(), 0) + service.refresh_value(key=PAGINATION_KEY) diff --git a/tests/test_global_config_signals.py b/tests/test_global_config_signals.py index b9e9ea2..a5fb6c8 100644 --- a/tests/test_global_config_signals.py +++ b/tests/test_global_config_signals.py @@ -1,10 +1,12 @@ from functools import partial +from unittest.mock import patch from django.core.cache import cache from django.test import TestCase from django_gc.models import GlobalConfig from django_gc.services import GlobalConfigInitializationService, GlobalConfigService +from django_gc.services.cache import CacheBackend from django_gc.signals.callbacks import refresh_global_config_value_safely, refresh_global_configs_cache_safely from django_gc.signals.refresh_global_configs_cache import refresh_global_configs_cache @@ -62,12 +64,12 @@ def test_safe_refresh_does_not_propagate_cache_failure(self) -> None: Simulate a failed post-commit cache refresh and verify that the exception is logged and contained. """ - class BrokenCache: - def get_lock(self, **_kwargs: object) -> object: - raise RuntimeError('cache unavailable') - - self.service._cache = BrokenCache() # type: ignore[assignment] - with self.assertLogs('django_gc.signals.callbacks', level='ERROR') as log_context: + with ( + patch.object(CacheBackend, 'is_shared', True), + patch.object(self.service._cache, 'get_lock', side_effect=RuntimeError('cache unavailable')) as get_lock, + self.assertLogs('django_gc.signals.callbacks', level='ERROR') as log_context + ): refresh_global_configs_cache_safely() + get_lock.assert_called_once() self.assertEqual(len(log_context.records), 1) diff --git a/tests/test_key_names.py b/tests/test_key_names.py index 2fb5445..d370c07 100644 --- a/tests/test_key_names.py +++ b/tests/test_key_names.py @@ -1,4 +1,5 @@ from dataclasses import replace +from unittest.mock import patch from django.core.cache import cache from django.core.exceptions import ImproperlyConfigured, PermissionDenied @@ -11,6 +12,7 @@ from django_gc.models import GlobalConfig from django_gc.registry import authorize_changes from django_gc.services import GlobalConfigInitializationService, GlobalConfigService +from django_gc.services.cache import CacheBackend from tests.definitions import TEST_DEFINITIONS @@ -54,6 +56,7 @@ class PreviousKeysTestCase(TestCase): Exercise cache lookups, encrypted values, conflicting old rows and provider protections. """ + @patch.object(CacheBackend, 'is_shared', True) def test_initialization_preserves_value_and_old_cache_cannot_override_current_value(self) -> None: """ Copy a previous value into the missing canonical row and verify that an old cache entry cannot diff --git a/tests/test_task.py b/tests/test_task.py index 0bbaa3b..b970d9a 100644 --- a/tests/test_task.py +++ b/tests/test_task.py @@ -1,8 +1,11 @@ +from unittest.mock import patch + from django.core.cache import cache from django.test import TestCase from django_gc.models import GlobalConfig from django_gc.services import GlobalConfigService +from django_gc.services.cache import CacheBackend from django_gc.tasks import refresh_global_configs_cache @@ -17,6 +20,7 @@ def setUp(self) -> None: def tearDown(self) -> None: cache.clear() + @patch.object(CacheBackend, 'is_shared', True) def test_task_refreshes_snapshot(self) -> None: """ Call the refresh task and check that it publishes the complete snapshot. diff --git a/uv.lock b/uv.lock index e1369a9..8986889 100644 --- a/uv.lock +++ b/uv.lock @@ -405,7 +405,7 @@ wheels = [ [[package]] name = "django-gc" -version = "1.1.5" +version = "1.1.6" source = { editable = "." } dependencies = [ { name = "cryptography" }, From c8a72796f1149b8ec63d5d1931c80604ea894207 Mon Sep 17 00:00:00 2001 From: Raman Marozau Date: Thu, 26 Nov 2026 02:34:19 +0300 Subject: [PATCH 2/3] v1.1.6 Fix secure --- .github/workflows/docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index db341b0..63b8efb 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -70,7 +70,7 @@ jobs: permissions: contents: read steps: - - uses: actions/checkout@3d3c42e5aac5ba805da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} fetch-depth: 0 From 9fe46dd9d94f4e97fb1def33a7a7160d415ac59e Mon Sep 17 00:00:00 2001 From: Raman Marozau Date: Thu, 26 Nov 2026 02:45:14 +0300 Subject: [PATCH 3/3] v1.1.6 Fix secure --- .github/docs/README.md | 3 +- .github/workflows/dispatch-tests.yml | 40 +++++++++++++++++++ .github/workflows/testing.yml | 19 +++++++-- docs/content/contrib.md | 2 +- .../current/contrib.md | 2 +- 5 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/dispatch-tests.yml diff --git a/.github/docs/README.md b/.github/docs/README.md index cffabf5..5f1354c 100644 --- a/.github/docs/README.md +++ b/.github/docs/README.md @@ -1,7 +1,8 @@ # Deploy the Django-GC documentation Pushes to any branch and pull requests run **Security checks**. -Pushes to protected branches also run the test workflow. To deploy, +The branch protection check dispatches testing for the current head of a protected branch. +Pushes to unprotected branches create no testing jobs. To deploy, run **Documentation** on `main` or dispatch it from another workflow. The release workflow dispatches it after PyPI accepts the package. It passes the release commit, which must belong to `main`. A manual run diff --git a/.github/workflows/dispatch-tests.yml b/.github/workflows/dispatch-tests.yml new file mode 100644 index 0000000..2484771 --- /dev/null +++ b/.github/workflows/dispatch-tests.yml @@ -0,0 +1,40 @@ +name: Dispatch tests for protected branches + +on: + workflow_run: + workflows: [Security checks] + types: [requested] + +permissions: {} + +jobs: + dispatch: + name: Dispatch testing for the protected branch head + if: github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository + permissions: + actions: write + contents: read + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Check branch protection and dispatch testing + shell: bash + env: + GH_TOKEN: ${{ github.token }} + BRANCH: ${{ github.event.workflow_run.head_branch }} + SOURCE_SHA: ${{ github.event.workflow_run.head_sha }} + run: | + if [[ -z "$BRANCH" || ! "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::Missing push branch or commit." + exit 1 + fi + + protected_heads=$(gh api --paginate "repos/$GITHUB_REPOSITORY/branches?protected=true&per_page=100") + is_protected_head=$(jq -rs --arg branch "$BRANCH" --arg sha "$SOURCE_SHA" \ + 'any(.[][]; .name == $branch and .commit.sha == $sha)' <<< "$protected_heads") + if [[ "$is_protected_head" != true ]]; then + echo "The pushed commit is no longer the head of a protected branch, or the branch is unprotected." + exit 0 + fi + + gh workflow run testing.yml --repo "$GITHUB_REPOSITORY" --ref "$BRANCH" -f "expected_sha=$SOURCE_SHA" diff --git a/.github/workflows/testing.yml b/.github/workflows/testing.yml index 3a5d91b..082ec10 100644 --- a/.github/workflows/testing.yml +++ b/.github/workflows/testing.yml @@ -1,9 +1,12 @@ name: Testing Django-GC pipeline on: - push: - branches: ['**'] workflow_dispatch: + inputs: + expected_sha: + description: Expected branch HEAD for an automatic dispatch + type: string + required: false workflow_call: inputs: source_sha: @@ -19,11 +22,21 @@ env: jobs: lint: - if: github.event_name != 'push' || github.ref_protected name: Python lint, types and Django checks runs-on: ubuntu-latest timeout-minutes: 10 steps: + - name: Verify the dispatch commit + if: github.event_name == 'workflow_dispatch' && inputs.expected_sha != '' + shell: bash + env: + EXPECTED_SHA: ${{ inputs.expected_sha }} + run: | + if [[ "$GITHUB_SHA" != "$EXPECTED_SHA" ]]; then + echo "::error::The branch advanced before the test workflow started." + exit 1 + fi + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.source_sha || github.sha }} diff --git a/docs/content/contrib.md b/docs/content/contrib.md index c61d526..c25f4de 100644 --- a/docs/content/contrib.md +++ b/docs/content/contrib.md @@ -73,7 +73,7 @@ npm run docs:serve ## CI, releases and deployment -Pushes to any branch and pull requests run Security checks. Pushes to protected branches also run the test pipeline. The test pipeline uses the dependency lock, verifies the Django migration state, runs the Python and Django matrix, builds both Python distributions and verifies the English and Russian documentation. The security workflow scans secrets, Python, Django templates, documentation JavaScript and TypeScript, and workflow files. It audits locked Python and npm dependencies. +Pushes to any branch and pull requests run Security checks. The branch protection check dispatches the test pipeline for the current head of a protected branch. Pushes to unprotected branches create no testing jobs. Manual test runs are available under **Actions**. The test pipeline uses the dependency lock, verifies the Django migration state, runs the Python and Django matrix, builds both Python distributions and verifies the English and Russian documentation. The security workflow scans secrets, Python, Django templates, documentation JavaScript and TypeScript, and workflow files. It audits locked Python and npm dependencies. The release workflow scans the release revision, verifies it matches the current head of `main` and requires a successful `testing.yml` run for that exact SHA on `main`. Publish only after the test run finishes. Run manual publishing from `main`. After uploading wheel and sdist to PyPI, the workflow dispatches the documentation workflow for the published commit. The documentation workflow checks ancestry and reuses the test result for the selected revision before deploying over SSH. The preparation workflow installs the deployment files in the SSH user’s home directory. The deploy job streams the selected source archive to the server, and the SSH account builds it with Docker. If the container fails its health check, the deployment script restores the previous image and port. diff --git a/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md b/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md index ce21b24..a3762bf 100644 --- a/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md +++ b/docs/i18n/ru/docusaurus-plugin-content-docs/current/contrib.md @@ -97,7 +97,7 @@ npm run docs:serve ## CI, публикация и деплой -Push в любую ветку и pull request запускают проверки безопасности. При push в защищённую ветку также запускаются тесты. Тестовый workflow проверяет lock-файл и состояние миграций Django, прогоняет матрицу Python и Django, собирает wheel и sdist, а также проверяет и собирает обе языковые версии документации. Workflow безопасности проверяет секреты, Python, шаблоны Django, JavaScript и TypeScript документации и файлы GitHub Actions. Отдельно выполняется аудит закреплённых зависимостей Python и npm. +Push в любую ветку и pull request запускают проверки безопасности. При push в защищённую ветку тесты запускаются для её актуального коммита. Push в обычную ветку не создаёт тестовых задач. Тесты можно запустить вручную во вкладке **Actions**. Тестовый workflow проверяет lock-файл и состояние миграций Django, прогоняет матрицу Python и Django, собирает wheel и sdist, а также проверяет и собирает обе языковые версии документации. Workflow безопасности проверяет секреты, Python, шаблоны Django, JavaScript и TypeScript документации и файлы GitHub Actions. Отдельно выполняется аудит закреплённых зависимостей Python и npm. Релизный workflow сканирует коммит, сверяет его с текущей вершиной `main` и требует успешный запуск `testing.yml` для этого SHA в `main`. Дождитесь завершения тестов перед публикацией. Ручную публикацию запускайте из `main`. После загрузки wheel и sdist в PyPI запускается деплой документации для опубликованного коммита. Workflow документации проверяет принадлежность коммита ветке и использует результат уже пройденных тестов перед деплоем по SSH. Workflow подготовки устанавливает файлы деплоя в домашний каталог SSH-пользователя. Деплой передаёт на сервер архив выбранного коммита, и SSH-пользователь собирает его через Docker. При ошибке проверки готовности скрипт восстанавливает прежний образ и порт.