diff --git a/.evergreen/generated_configs/tasks.yml b/.evergreen/generated_configs/tasks.yml index 8e2214c680..be4adf52c4 100644 --- a/.evergreen/generated_configs/tasks.yml +++ b/.evergreen/generated_configs/tasks.yml @@ -213,6 +213,19 @@ tasks: TEST_NAME: fuzz SUB_TEST_NAME: fuzz UV_PYTHON: "3.13" + - command: subprocess.exec + params: + binary: bash + args: + - .evergreen/scripts/capture-fuzz-corpus.sh + working_dir: src + include_expansions_in_env: + - FUZZ_CORPUS_MAX_UNITS + - FUZZ_CORPUS_MAX_UNIT_BYTES + - AWS_ACCESS_KEY_ID + - AWS_SECRET_ACCESS_KEY + - AWS_SESSION_TOKEN + type: test tags: [fuzz, fuzz-nightly] # Getdata tests @@ -2844,6 +2857,22 @@ tasks: - func: send dashboard data tags: [perf] + # Sanitizer tests + - name: test-sanitizer + commands: + - func: run server + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + - func: run tests + vars: + AUTH: noauth + SSL: nossl + TOPOLOGY: standalone + TEST_NAME: sanitizer + tags: [sanitizer, pr] + # Search index tests - name: test-search-index-helpers commands: @@ -4816,29 +4845,6 @@ tasks: - sync - free-threaded - # String query preview tests - - name: test-string-query-preview-v8.2-python3.15-noauth-ssl-replica-set - commands: - - func: run server - vars: - AUTH: noauth - SSL: ssl - TOPOLOGY: replica_set - VERSION: "8.2" - - func: run tests - vars: - AUTH: noauth - SSL: ssl - TOPOLOGY: replica_set - VERSION: "8.2" - UV_PYTHON: "3.15" - tags: - - test-string-query-preview - - server-8.2 - - python-3.15 - - replica_set-noauth-ssl - - noauth - # Test non standard tests - name: test-non-standard-v4.4-python3.12-noauth-ssl-replica-set commands: diff --git a/.evergreen/generated_configs/variants.yml b/.evergreen/generated_configs/variants.yml index 67d069f438..c9c14e364f 100644 --- a/.evergreen/generated_configs/variants.yml +++ b/.evergreen/generated_configs/variants.yml @@ -89,7 +89,7 @@ buildvariants: - name: .auth-aws !.auth-aws-web-identity !.auth-aws-ec2 display_name: Auth AWS macOS run_on: - - macos-14 + - macos-15-amd64 tags: [pr] - name: auth-aws-ecs-ubuntu-24 tasks: @@ -186,7 +186,6 @@ buildvariants: - name: encryption-rhel8 tasks: - name: .test-non-standard !.python-3.15t - - name: .test-string-query-preview display_name: Encryption RHEL8 run_on: - rhel8.10-small @@ -198,10 +197,9 @@ buildvariants: tasks: - name: .test-non-standard !.cov !.python-3.15t - name: .test-non-standard-no-cov !.python-3.15t - - name: .test-string-query-preview display_name: Encryption macOS run_on: - - macos-14 + - macos-15-amd64 batchtime: 1440 expansions: TEST_NAME: encryption @@ -210,7 +208,6 @@ buildvariants: tasks: - name: .test-non-standard !.cov !.python-3.15t - name: .test-non-standard-no-cov !.python-3.15t - - name: .test-string-query-preview display_name: Encryption Win64 run_on: - windows-2022-latest-small @@ -221,7 +218,6 @@ buildvariants: - name: encryption-crypt_shared-rhel8 tasks: - name: .test-non-standard !.python-3.15t - - name: .test-string-query-preview display_name: Encryption crypt_shared RHEL8 run_on: - rhel8.10-small @@ -234,10 +230,9 @@ buildvariants: tasks: - name: .test-non-standard !.cov !.python-3.15t - name: .test-non-standard-no-cov !.python-3.15t - - name: .test-string-query-preview display_name: Encryption crypt_shared macOS run_on: - - macos-14 + - macos-15-amd64 batchtime: 1440 expansions: TEST_NAME: encryption @@ -247,7 +242,6 @@ buildvariants: tasks: - name: .test-non-standard !.cov !.python-3.15t - name: .test-non-standard-no-cov !.python-3.15t - - name: .test-string-query-preview display_name: Encryption crypt_shared Win64 run_on: - windows-2022-latest-small @@ -304,7 +298,7 @@ buildvariants: - name: .test-standard-auth .auth !.free-threaded display_name: Auth Enterprise macOS run_on: - - macos-14 + - macos-15-amd64 expansions: TEST_NAME: enterprise_auth AUTH: auth @@ -448,7 +442,7 @@ buildvariants: - name: .ocsp-rsa !.ocsp-staple .4.4 display_name: OCSP macOS run_on: - - macos-14 + - macos-15-amd64 batchtime: 10080 # Oidc auth tests @@ -474,7 +468,7 @@ buildvariants: - name: "!.auth_oidc_remote .auth_oidc" display_name: Auth OIDC macOS run_on: - - macos-14 + - macos-15-amd64 batchtime: 1440 - name: auth-oidc-win64 tasks: @@ -510,7 +504,7 @@ buildvariants: - name: .test-standard !.python-3.15t .async .replica_set-noauth-ssl display_name: PyOpenSSL macOS run_on: - - macos-14 + - macos-15-amd64 batchtime: 1440 expansions: SUB_TEST_NAME: pyopenssl @@ -536,6 +530,17 @@ buildvariants: SUB_TEST_NAME: pyopenssl tags: [pr] + # Sanitizer tests + - name: sanitizer-rhel8 + tasks: + - name: .sanitizer + display_name: Sanitizer RHEL8 + run_on: + - rhel8.10-large + expansions: + VERSION: "9.0" + tags: [pr] + # Search index tests - name: search-index-helpers-rhel8 tasks: @@ -672,7 +677,7 @@ buildvariants: - name: .test-standard display_name: "* Test macOS" run_on: - - macos-14 + - macos-15-amd64 tags: [standard-non-linux] - name: test-macos-arm64 tasks: @@ -684,7 +689,7 @@ buildvariants: - name: .test-standard .server-latest display_name: "* Test macOS Arm64" run_on: - - macos-14-arm64 + - macos-15-arm64 tags: [standard-non-linux] - name: test-win64 tasks: @@ -727,14 +732,14 @@ buildvariants: - name: .test-numpy display_name: Test Numpy macOS run_on: - - macos-14 + - macos-15-amd64 tags: [binary, vector] - name: test-numpy-macos-arm64 tasks: - name: .test-numpy display_name: Test Numpy macOS Arm64 run_on: - - macos-14-arm64 + - macos-15-arm64 tags: [binary, vector] - name: test-numpy-win64 tasks: diff --git a/.evergreen/scripts/capture-fuzz-corpus.sh b/.evergreen/scripts/capture-fuzz-corpus.sh new file mode 100755 index 0000000000..438c7f6754 --- /dev/null +++ b/.evergreen/scripts/capture-fuzz-corpus.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# PYTHON-6178: capture coverage-increasing inputs from a fuzz run and open +# an automated PR growing fuzz/corpus/. Runs as the last command of the +# nightly "fuzz" task, while the scratch corpus exists; manual +# `evergreen patch --variant fuzz-rhel8 --task fuzz` runs capture too. +set -eu + +# Same environment as just.sh: venv on PATH for a modern Python. +. "$(dirname "${BASH_SOURCE:-$0}")/setup-dev-env.sh" + +# No new units means no PR, and the github secrets flow is never touched. +uv run --no-sync python fuzz/capture_corpus.py +if [ -z "$(ls -A fuzz-scratch/capture 2>/dev/null || true)" ]; then + echo "No new fuzz corpus units; nothing to do." + exit 0 +fi + +# A unit found by a later target never ran through the earlier ones, so +# replay every unit through all targets before publishing. +replay=(fuzz-scratch/capture/*) +for target in fuzz_decode fuzz_decode_all fuzz_is_valid; do + echo "Replaying captured units against ${target}..." + if ! uv run --no-sync python "fuzz/${target}.py" "${replay[@]}" \ + -artifact_prefix="$PWD/fuzz-scratch/" -atheris_runs="${#replay[@]}" + then + echo "Captured unit fails ${target}; no corpus PR." >&2 + exit 1 + fi +done + +bash .evergreen/scripts/create-fuzz-corpus-pr.sh \ + fuzz-scratch/capture fuzz-scratch/capture-summary.md diff --git a/.evergreen/scripts/configure-env.sh b/.evergreen/scripts/configure-env.sh index 5e36125838..2143a56660 100755 --- a/.evergreen/scripts/configure-env.sh +++ b/.evergreen/scripts/configure-env.sh @@ -39,8 +39,7 @@ fi # Add the latest MongoDB toolchain bin dir to PATH if it exists, so that hosts # with an old system Python (e.g. RHEL8's 3.6) still get a modern interpreter # for tool installs like `uv tool install rust-just`. It goes after -# PYMONGO_BIN_DIR so the pinned uv (installed there by setup-uv.py) takes -# precedence over the toolchain's uv. +# PYMONGO_BIN_DIR so the project's uv takes precedence. if [ "Windows_NT" = "${OS:-}" ]; then _toolchain_bin="/cygdrive/c/Python/Current/Scripts" elif [ "$(uname -s)" == "Darwin" ]; then @@ -106,8 +105,9 @@ if [ "$DRIVERS_TOOLS" = "$PROJECT_DIRECTORY/drivers-evergreen-tools" ]; then # Write a uv config boundary into the submodule: it is vendored inside this # project, so uv run by the tools' own scripts would otherwise walk up to - # pyproject.toml and enforce our required-version pin. Write-if-absent, so an - # upstream uv.toml fails the submodule update loudly instead of being clobbered. + # pyproject.toml and apply this project's [tool.uv] settings. + # Write-if-absent, so an upstream uv.toml fails the submodule update loudly + # instead of being clobbered. if [ -d "${DRIVERS_TOOLS}" ] && [ ! -f "${DRIVERS_TOOLS}/uv.toml" ]; then cat < "${DRIVERS_TOOLS}/uv.toml" # Written by mongo-python-driver to stop uv's config discovery here; see diff --git a/.evergreen/scripts/create-fuzz-corpus-pr.sh b/.evergreen/scripts/create-fuzz-corpus-pr.sh new file mode 100755 index 0000000000..d24e677bff --- /dev/null +++ b/.evergreen/scripts/create-fuzz-corpus-pr.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -eu + +# Open (or update) the automated pull request that grows fuzz/corpus/ +# with freshly captured units. Arguments: 1 = captured units directory, +# 2 = capture summary markdown to use as the PR body. + +capture_dir="$1" +summary_file="$2" +today="$(date '+%m-%d-%Y')" + +# Shared github-app authentication, git branch and PR plumbing. +# shellcheck disable=SC1091 +. "$(dirname "${BASH_SOURCE[0]}")/github-pr-util.sh" + +acquire_github_token + +echo "Creating the git checkout..." +branch="fuzz-corpus-${today}" +prepare_bot_branch "$branch" + +mkdir -p fuzz/corpus +cp "$capture_dir"/* fuzz/corpus/ +if ! stage_and_commit "PYTHON-6178 Grow the BSON fuzz corpus (${today})" fuzz/corpus; then + echo "No new corpus units to commit; skipping PR creation." + exit 0 +fi +echo "Creating the git checkout... done." + +push_branch "$branch" +create_or_update_pr "$branch" "[Fuzz Corpus] ${today}" "$summary_file" diff --git a/.evergreen/scripts/create-spec-pr.sh b/.evergreen/scripts/create-spec-pr.sh index fb2dea1640..51561ef29f 100755 --- a/.evergreen/scripts/create-spec-pr.sh +++ b/.evergreen/scripts/create-spec-pr.sh @@ -1,127 +1,30 @@ #!/usr/bin/env bash set -eu -# Default to the drivers-evergreen-tools submodule when unset; a -# caller-provided DRIVERS_TOOLS wins, as in the other consumers. -tools="$(realpath -s "${DRIVERS_TOOLS:-./drivers-evergreen-tools}")" -pushd $tools/.evergreen/github_app || exit +# Open (or update) the automated pull request resyncing the spec tests. +# Arguments: 1 = resync summary text to use as the PR body. -owner="mongodb" -repo="mongo-python-driver" +summary_file="$1" +today="$(date '+%m-%d-%Y')" -# Bootstrap the app. -echo "bootstrapping" -source utils.sh -bootstrap drivers/comment-bot +# Shared github-app authentication, git branch and PR plumbing. +# shellcheck disable=SC1091 +. "$(dirname "${BASH_SOURCE[0]}")/github-pr-util.sh" -# Run the app. -source ./secrets-export.sh +acquire_github_token -# Get a github access token for the git checkout. -echo "Getting github token..." - -token=$(bash ./get-access-token.sh $repo $owner) -if [ -z "${token}" ]; then - echo "Failed to get github access token!" - popd || exit - exit 1 -fi -echo "Getting github token... done." -popd || exit - -# Make the git checkout and create a new branch. echo "Creating the git checkout..." -branch="spec-resync-"$(date '+%m-%d-%Y') - -git remote set-url origin https://x-access-token:${token}@github.com/$owner/$repo.git -# -B resets the branch if a reused checkout already has it, keeping reruns idempotent. -git checkout -B "$branch" "origin/main" +branch="spec-resync-${today}" +prepare_bot_branch "$branch" -# Attribute the commit to the bot user; fall back to the host identity. -bot_login="mongodb-drivers-pr-bot[bot]" -bot_id=$(curl -gsm 10 "https://api.github.com/users/${bot_login}" | jq -r '.id // empty' || true) -if [ -n "$bot_id" ]; then - git config user.name "$bot_login" - git config user.email "${bot_id}+${bot_login}@users.noreply.github.com" -fi - -git add ./test - -if git diff --cached --quiet && git diff --quiet --ignore-submodules=dirty; then +# The spec sync also updates the vendored public suffix list (cp_psl in +# resync-specs.sh), a tracked file outside test/. +if ! stage_and_commit "resyncing specs ${today}" ./test pymongo/public_suffix_list.dat; then echo "No spec changes to commit; skipping PR creation." - cat "$1" + cat "$summary_file" exit 0 fi - -git commit -am "resyncing specs $(date '+%m-%d-%Y')" echo "Creating the git checkout... done." -# Date-stamped branch: force-push makes same-day reruns idempotent; retry -# absorbs GitHub's intermittent 403s on the receive-pack endpoint. -push_ok=false -for _attempt in 1 2 3; do - if git push --force origin $branch; then - push_ok=true - break - fi - if [ "$_attempt" -lt 3 ]; then - echo "Push attempt ${_attempt} failed; retrying in 30s..." - sleep 30 - fi -done -if [ "$push_ok" != true ]; then - echo "Failed to push $branch after 3 attempts!" >&2 - exit 1 -fi - -# Build the payload as a file so the body content is always properly -# JSON-escaped, rather than interpolated into the command line as text. -payload_file=$(mktemp) -trap 'rm -f "$payload_file"' EXIT -jq -n \ - --arg title "[Spec Resync] $(date '+%m-%d-%Y')" \ - --arg head "${branch}" \ - --rawfile body "$1" \ - '{title: $title, body: $body, head: $head, base: "main"}' > "$payload_file" - -# Reuse an open PR for this branch (same-day rerun) instead of duplicating it. -existing_pr_json=$(curl -gs \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: Bearer $token" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - --url "https://api.github.com/repos/$owner/$repo/pulls?head=$owner:$branch&state=open") -existing_pr_url=$(echo "$existing_pr_json" | jq -r '.[0].html_url // empty') -if [ -n "$existing_pr_url" ]; then - existing_pr_number=$(echo "$existing_pr_json" | jq -r '.[0].number // empty') - if ! curl -sfX PATCH \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: Bearer $token" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - -d "{\"title\": \"[Spec Resync] $(date '+%m-%d-%Y')\", \"body\": $(jq -Rs . < "$1")}" \ - --url "https://api.github.com/repos/$owner/$repo/pulls/${existing_pr_number}" > /dev/null - then - echo "Failed to update PR summary!" >&2 - exit 1 - fi - echo "$existing_pr_url" - echo "Creating the PR... done. (PR already existed; branch and summary were updated)" - rm -rf $tools - exit 0 -fi - -resp=$(curl -L \ - -X POST \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: Bearer $token" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - -d "@${payload_file}" \ - --url https://api.github.com/repos/$owner/$repo/pulls) - -pr_url=$(echo "$resp" | jq -r '.html_url // empty') -if [ -z "$pr_url" ]; then - echo "Failed to create PR! API response:" - echo "$resp" | jq . - exit 1 -fi -echo "$pr_url" -echo "Creating the PR... done." +push_branch "$branch" +create_or_update_pr "$branch" "[Spec Resync] ${today}" "$summary_file" diff --git a/.evergreen/scripts/generate_config.py b/.evergreen/scripts/generate_config.py index 3589a81c86..123362a89a 100644 --- a/.evergreen/scripts/generate_config.py +++ b/.evergreen/scripts/generate_config.py @@ -3,6 +3,7 @@ import sys from itertools import product +from typing import TYPE_CHECKING from generate_config_utils import ( ALL_PYTHONS, @@ -36,7 +37,6 @@ write_variants_to_file, zip_cycle, ) -from shrub.v3.evg_build_variant import BuildVariant from shrub.v3.evg_command import ( FunctionCall, archive_targz_pack, @@ -49,6 +49,9 @@ from shrub.v3.evg_task import EvgTask, EvgTaskDependency, EvgTaskRef from utils import PERF_PYTHON_VERSION +if TYPE_CHECKING: + from shrub.v3.evg_build_variant import BuildVariant + ############## # Variants ############## @@ -151,7 +154,7 @@ def get_encryption_expansions(encryption): ): expansions = get_encryption_expansions(encryption) display_name = get_variant_name(encryption, host, **expansions) - tasks = [".test-non-standard !.python-3.15t", ".test-string-query-preview"] + tasks = [".test-non-standard !.python-3.15t"] if host != "rhel8": # Exclude coverage tasks (encryption suites exceed the 60-min timeout with # coverage overhead on macOS/win64). @@ -160,7 +163,6 @@ def get_encryption_expansions(encryption): tasks = [ ".test-non-standard !.cov !.python-3.15t", ".test-non-standard-no-cov !.python-3.15t", - ".test-string-query-preview", ] variant = create_variant( tasks, @@ -518,14 +520,39 @@ def create_doctests_variants(): def create_fuzz_variants(): + # Two variants for the two fuzz flows: the regression reproducers run + # on every PR, the time-boxed fuzzing runs nightly. The nightly variant + # carries no "pr" tag, so PR patch builds never select it, while its + # default patchability keeps it manually runnable + # (`evergreen patch --variant fuzz-rhel8 --task fuzz`). The host needs + # CPython, which the rhel8 toolchain provides. host = HOSTS["rhel8"] - # Regression test on every PR. - name = get_variant_name("Fuzz Regression", host) - pr_variant = create_variant([".fuzz-regression"], name, host=host, tags=["pr"]) - # Fuzzing requires CPython on Linux/macOS; use a pinned CPython on RHEL8. - name = get_variant_name("Fuzz", host) - nightly = create_variant([".fuzz-nightly"], name, host=host, batchtime=BATCHTIME_DAY) - return [pr_variant, nightly] + return [ + create_variant( + [".fuzz-regression"], get_variant_name("Fuzz Regression", host), host=host, tags=["pr"] + ), + create_variant( + [".fuzz-nightly"], get_variant_name("Fuzz", host), host=host, batchtime=BATCHTIME_DAY + ), + ] + + +def create_sanitizer_variants() -> list[BuildVariant]: + # ASan/UBSan checks on every PR (PYTHON-6048). The rhel8 toolchain + # provides the instrumented CPython (utils.SANITIZER_PYTHON), and the + # large distro gives ASan's shadow memory and redzones room for the + # ~6GiB test_encode_size_limit allocation, so no test is skipped. + host = DEFAULT_HOST + return [ + create_variant( + [".sanitizer"], + get_variant_name("Sanitizer", host), + host=host, + run_on="rhel8.10-large", + version=MAX_VERSION, + tags=["pr"], + ) + ] def create_atlas_connect_variants(): @@ -728,19 +755,19 @@ def make_task(topology, auth, ssl, sync, python, extra_tags=(), **extra_vars): # The pinned pr tasks: the boundary Pythons per server version, stable as CPYTHONS changes. for version, combos in sorted(SERVER_VERSION_PR_PYTHONS.items()): for (topology, auth, ssl), python in sorted(combos.items()): - for sync in SYNCS: - tasks.append( - make_task( - topology, - auth, - ssl, - sync, - python, - extra_tags=("pr", version), - VERSION=version, - COVERAGE="1", - ) + tasks.extend( + make_task( + topology, + auth, + ssl, + sync, + python, + extra_tags=("pr", version), + VERSION=version, + COVERAGE="1", ) + for sync in SYNCS + ) return tasks @@ -822,34 +849,6 @@ def create_test_non_standard_tasks(): return tasks -def create_string_query_preview_tasks(): - """Tasks for the preview Queryable Encryption string query types. - - The preview query types need a server that is at least 8.2 and older than - 9.0, and ALL_VERSIONS jumps straight from 8.0 to 9.0, so they have nowhere - to run without a dedicated task. setup_tests.py pins the released - pymongocrypt for 8.x, which bundles a libmongocrypt still carrying the - preview types. - """ - python = CPYTHONS[-1] - topology = "replica_set" - auth, ssl = get_standard_auth_ssl(topology) - expansions = dict(AUTH=auth, SSL=ssl, TOPOLOGY=topology, VERSION="8.2") - tags = [ - "test-string-query-preview", - "server-8.2", - f"python-{python}", - f"{topology}-{auth}-{ssl}", - auth, - ] - name = get_task_name("test-string-query-preview", python=python, **expansions) - server_func = FunctionCall(func="run server", vars=expansions) - test_vars = expansions.copy() - test_vars["UV_PYTHON"] = python - test_func = FunctionCall(func="run tests", vars=test_vars) - return [EvgTask(name=name, tags=tags, commands=[server_func, test_func])] - - def create_test_standard_auth_tasks(): """We only use auth on sharded clusters""" tasks = [] @@ -968,10 +967,40 @@ def create_fuzz_tasks(): tags = ["fuzz", "fuzz-nightly"] test_vars = dict(TEST_NAME="fuzz", SUB_TEST_NAME="fuzz", UV_PYTHON="3.13") test_func = FunctionCall(func="run tests", vars=test_vars) - tasks.append(EvgTask(name="fuzz", tags=tags, commands=[test_func])) + # PYTHON-6178: while the scratch corpus still exists, capture the new + # coverage-increasing inputs, replay them through every target so a + # unit that fails one is never published, and open an automated PR + # growing fuzz/corpus/. + capture_cmd = get_subprocess_exec( + args=[".evergreen/scripts/capture-fuzz-corpus.sh"], + include_expansions_in_env=[ + "FUZZ_CORPUS_MAX_UNITS", + "FUZZ_CORPUS_MAX_UNIT_BYTES", + # The capture bootstraps the comment-bot github app, whose + # secrets live in AWS Secrets Manager; pass the assumed-role + # credentials as resync_specs and backport-pr also do. + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + "AWS_SESSION_TOKEN", + ], + ) + tasks.append(EvgTask(name="fuzz", tags=tags, commands=[test_func, capture_cmd])) return tasks +def create_sanitizer_tasks(): + # VERSION comes from the variant: a task-level VERSION would trip the + # pr-tasks-run-coverage rule, and coverage under ASan is not useful. + tags = ["sanitizer", "pr"] + expansions = dict(AUTH="noauth", SSL="nossl", TOPOLOGY="standalone") + server_func = FunctionCall(func="run server", vars=expansions) + test_vars = expansions.copy() + test_vars["TEST_NAME"] = "sanitizer" + test_func = FunctionCall(func="run tests", vars=test_vars) + name = get_task_name("test-sanitizer") + return [EvgTask(name=name, tags=tags, commands=[server_func, test_func])] + + def create_kms_tasks(): tasks = [] for kms_type in ["gcp", "azure"]: diff --git a/.evergreen/scripts/generate_config_utils.py b/.evergreen/scripts/generate_config_utils.py index 0ba291ab5b..f5884a633b 100644 --- a/.evergreen/scripts/generate_config_utils.py +++ b/.evergreen/scripts/generate_config_utils.py @@ -66,8 +66,8 @@ class Host: HOSTS["win64"] = Host("win64", "windows-64-vsMulti-small", "Win64", dict()) HOSTS["win-latest"] = Host("win-latest", "windows-2022-latest-small", "WinLatest", dict()) HOSTS["win32"] = Host("win32", "windows-64-vsMulti-small", "Win32", dict()) -HOSTS["macos"] = Host("macos", "macos-14", "macOS", dict()) -HOSTS["macos-arm64"] = Host("macos-arm64", "macos-14-arm64", "macOS Arm64", dict()) +HOSTS["macos"] = Host("macos", "macos-15-amd64", "macOS", dict()) +HOSTS["macos-arm64"] = Host("macos-arm64", "macos-15-arm64", "macOS Arm64", dict()) HOSTS["ubuntu22"] = Host("ubuntu22", "ubuntu2204-small", "Ubuntu-22", dict()) HOSTS["ubuntu24"] = Host("ubuntu24", "ubuntu2404-small", "Ubuntu-24", dict()) HOSTS["perf"] = Host("perf", "rhel90-dbx-perf-large", "", dict()) @@ -85,6 +85,7 @@ class Host: "rhel82-arm64-small", "amazon2023-arm64-latest-large-m8g", ], + strict=True, ): HOSTS[name] = Host(name, run_on, name, dict()) diff --git a/.evergreen/scripts/github-pr-util.sh b/.evergreen/scripts/github-pr-util.sh new file mode 100755 index 0000000000..e2b2d87de4 --- /dev/null +++ b/.evergreen/scripts/github-pr-util.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +# Shared plumbing for the automated PR workflows (spec resync and fuzz +# corpus growth): github-app authentication, branch preparation, force +# pushing with retries, and create-or-update against the GitHub API. +# +# Source this file from a wrapper script run from the repository root +# (where the drivers-evergreen-tools submodule lives); it is not meant to +# be executed directly. Defines OWNER, REPO and the functions below; +# requires curl, jq and git. + +OWNER="mongodb" +REPO="mongo-python-driver" + +# Authenticate with the github app in drivers-evergreen-tools and set +# GITHUB_TOKEN. Exits the caller if no token can be obtained. +acquire_github_token() { + # Default to the drivers-evergreen-tools submodule when unset; a + # caller-provided DRIVERS_TOOLS wins, as in the other consumers. + local tools + tools="$(realpath -s "${DRIVERS_TOOLS:-./drivers-evergreen-tools}")" + pushd "$tools/.evergreen/github_app" || exit + + # Bootstrap the app. + echo "bootstrapping" + # shellcheck disable=SC1091 + source utils.sh + bootstrap drivers/comment-bot + + # Run the app. + # shellcheck disable=SC1091 + source ./secrets-export.sh + + # Get a github access token for the git checkout. + echo "Getting github token..." + + GITHUB_TOKEN=$(bash ./get-access-token.sh "$REPO" "$OWNER") + if [ -z "${GITHUB_TOKEN}" ]; then + echo "Failed to get github access token!" + popd || exit + exit 1 + fi + echo "Getting github token... done." + popd || exit +} + +# Prepare the git checkout: point origin at the repo with token auth, +# check out fresh from origin/main (-B resets a reused checkout, +# keeping reruns idempotent), and attribute commits to the drivers PR bot +# when its GitHub id is resolvable. +prepare_bot_branch() { + local branch="$1" + + git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@github.com/${OWNER}/${REPO}.git" + git checkout -B "$branch" "origin/main" + + local bot_login="mongodb-drivers-pr-bot[bot]" bot_id + bot_id=$(curl -gsm 10 "https://api.github.com/users/${bot_login}" | jq -r '.id // empty' || true) + if [ -n "$bot_id" ]; then + git config user.name "$bot_login" + git config user.email "${bot_id}+${bot_login}@users.noreply.github.com" + fi +} + +# Stage the given paths and commit them. Arguments: the commit message, +# then the paths to stage. Returns 1 when the tree was already clean, so +# the caller can skip PR creation. Git failures exit the caller: errexit +# is suspended while this function runs in an "if" condition, so every +# fallible command is guarded explicitly. +stage_and_commit() { + local message="$1" + shift + + git add "$@" || exit + if git diff --cached --quiet && git diff --quiet --ignore-submodules=dirty; then + return 1 + fi + git commit -m "$message" || exit +} + +# Push to origin. Force-pushing makes same-day reruns of a +# date-stamped branch idempotent; the retries absorb GitHub's +# intermittent 403s on the receive-pack endpoint. Exits the caller after +# 3 failed attempts. +push_branch() { + local branch="$1" + + local push_ok=false + local attempt + for attempt in 1 2 3; do + if git push --force origin "$branch"; then + push_ok=true + break + fi + if [ "$attempt" -lt 3 ]; then + echo "Push attempt ${attempt} failed; retrying in 30s..." + sleep 30 + fi + done + if [ "$push_ok" != true ]; then + echo "Failed to push $branch after 3 attempts!" + exit 1 + fi +} + +# Create a PR from , or, when an open PR is already attached to +# that branch (a same-day rerun), update its title and body instead. +# Arguments: the branch name, the PR title, and the path to a file with +# the PR body. Echoes the PR url and exits the caller if GitHub rejects +# the request. +create_or_update_pr() { + local branch="$1" title="$2" summary_file="$3" + + # Build the payload as a file so the body content is always properly + # JSON-escaped, rather than interpolated into the command line as text. + # Not local: the EXIT trap below must still see it after this function + # returns. + payload_file=$(mktemp) + trap 'rm -f "$payload_file"' EXIT + jq -n \ + --arg title "$title" \ + --arg head "${branch}" \ + --rawfile body "$summary_file" \ + '{title: $title, body: $body, head: $head, base: "main"}' > "$payload_file" + + # Reuse an open PR for this branch (same-day rerun) instead of duplicating it. + local existing_pr_json existing_pr_url existing_pr_number + existing_pr_json=$(curl -gs \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + --url "https://api.github.com/repos/$OWNER/$REPO/pulls?head=$OWNER:$branch&state=open") + existing_pr_url=$(echo "$existing_pr_json" | jq -r '.[0].html_url // empty') + if [ -n "$existing_pr_url" ]; then + existing_pr_number=$(echo "$existing_pr_json" | jq -r '.[0].number // empty') + if ! curl -sfX PATCH \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + -d "$(jq -n --arg title "$title" --rawfile body "$summary_file" '{title: $title, body: $body}')" \ + --url "https://api.github.com/repos/$OWNER/$REPO/pulls/${existing_pr_number}" > /dev/null + then + echo "Failed to update PR summary!" + exit 1 + fi + echo "$existing_pr_url" + echo "Creating the PR... done. (PR already existed; branch and summary were updated)" + return 0 + fi + + local resp pr_url + resp=$(curl -L \ + -X POST \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer $GITHUB_TOKEN" \ + -H "X-GitHub-Api-Version: 2022-11-28" \ + -d "@${payload_file}" \ + --url "https://api.github.com/repos/$OWNER/$REPO/pulls") + + pr_url=$(echo "$resp" | jq -r '.html_url // empty') + if [ -z "$pr_url" ]; then + echo "Failed to create PR! API response:" + echo "$resp" | jq . + exit 1 + fi + echo "$pr_url" + echo "Creating the PR... done." +} diff --git a/.evergreen/scripts/install-dependencies.sh b/.evergreen/scripts/install-dependencies.sh index 93b62ce6b6..3ad8d2e9d5 100755 --- a/.evergreen/scripts/install-dependencies.sh +++ b/.evergreen/scripts/install-dependencies.sh @@ -30,12 +30,12 @@ if [ "Windows_NT" = "${OS:-}" ]; then else export PYMONGO_BIN_DIR_POSIX="$PYMONGO_BIN_DIR" fi -# UV_TOOL_BIN_DIR is uv's name for the same dir (setup-uv.py reads both). +# UV_TOOL_BIN_DIR is uv's name for the same dir (setup_uv.py reads both). # UV_TOOL_DIR is left to ensure_uv.sh. export UV_TOOL_BIN_DIR="${UV_TOOL_BIN_DIR:-$PYMONGO_BIN_DIR}" # Ensure the bin dir is on PATH: hosts without env.sh (e.g. auth-aws-ecs) never -# export it, so a fresh pinned install there would be invisible to the probe +# export it, so a fresh uv install there would be invisible to the probe # below and to later steps like `uv tool install` and `uv sync`. case ":$PATH:" in *":$PYMONGO_BIN_DIR_POSIX:"*) ;; @@ -43,13 +43,14 @@ case ":$PATH:" in esac # Compute the setup script path once (native Windows path on cygwin). -_uv_setup_script="$HERE/setup-uv.py" +_uv_setup_script="$HERE/setup_uv.py" if [ "Windows_NT" = "${OS:-}" ]; then _uv_setup_script="$(cygpath -m "$_uv_setup_script")" fi -# Skip setup when the pinned uv is already installed: `setup-uv.py --check` -# compares the uv on PATH with the required-version pin, without side effects. +# Skip setup when a suitable uv is already installed: `setup_uv.py --check` +# verifies the required-version pin, or the project-controlled uv in +# UV_TOOL_BIN_DIR when unpinned, without side effects. # A full `uv sync` here would download Python and install/build dependencies # just to make this decision, and would run before setup-uv-python.sh sets # UV_PYTHON, creating the environment twice on local dev. @@ -79,7 +80,7 @@ if [ "$_need_setup" = "1" ]; then # and no required-version check is triggered. python3 "$_uv_setup_script" - # Re-source env.sh so the values setup-uv.py wrote are available. + # Re-source env.sh so the values setup_uv.py wrote are available. if [ -f $HERE/env.sh ]; then . $HERE/env.sh fi diff --git a/.evergreen/scripts/resync-all-specs.sh b/.evergreen/scripts/resync-all-specs.sh index 11dd2e65ba..51d365cb88 100755 --- a/.evergreen/scripts/resync-all-specs.sh +++ b/.evergreen/scripts/resync-all-specs.sh @@ -32,14 +32,14 @@ PR_DESC="spec_sync.txt" if ! [ -n "${CI:-}" ] then # we're running locally - python3 ./.evergreen/scripts/resync-all-specs.py + python3 ./.evergreen/scripts/resync_all_specs.py else # Use the newest mongodbtoolchain python; the default python3 may be too old. PY=$(ls -1d /opt/mongodbtoolchain/v*/bin/python3 2>/dev/null | sort -V | tail -1) [ -n "$PY" ] || PY=python3 [ "$("$PY" -c 'import sys; print(sys.version_info >= (3, 7))' 2>/dev/null)" = True ] \ - || { echo "Error: $PY is not Python 3.7+, which resync-all-specs.py requires." >&2; exit 1; } - "$PY" ./.evergreen/scripts/resync-all-specs.py --filename "$PR_DESC" + || { echo "Error: $PY is not Python 3.7+, which resync_all_specs.py requires." >&2; exit 1; } + "$PY" ./.evergreen/scripts/resync_all_specs.py --filename "$PR_DESC" if [[ -f $PR_DESC ]]; then # changes were made -> call scrypt to create PR for us .evergreen/scripts/create-spec-pr.sh "$PR_DESC" diff --git a/.evergreen/scripts/resync-all-specs.py b/.evergreen/scripts/resync_all_specs.py similarity index 100% rename from .evergreen/scripts/resync-all-specs.py rename to .evergreen/scripts/resync_all_specs.py diff --git a/.evergreen/scripts/run_tests.py b/.evergreen/scripts/run_tests.py index 9c3cdf13f5..4e94cca970 100644 --- a/.evergreen/scripts/run_tests.py +++ b/.evergreen/scripts/run_tests.py @@ -85,6 +85,16 @@ def handle_green_framework() -> None: LOGGER.info(f"Running tests with {GREEN_FRAMEWORK}...") +def handle_load_balancer_marker() -> None: + """Select the full default suite plus the load-balancer-marked tests. + + The last ``-m`` wins over the one setup_tests.py wrote, and + pytest_conf.py grants the implicit default markers only to unmarked + tests, so the expression needs an explicit ``load_balancer`` term. + """ + TEST_ARGS.extend(["-m", "default or default_async or load_balancer"]) + + def handle_c_ext() -> None: if platform.python_implementation() != "CPython": return @@ -194,6 +204,8 @@ def run() -> None: # Handle green framework first so they can patch modules. if GREEN_FRAMEWORK: handle_green_framework() + elif TEST_NAME == "load_balancer": + handle_load_balancer_marker() # Ensure C extensions if applicable. if not os.environ.get("NO_EXT"): diff --git a/.evergreen/scripts/setup-dev-env.sh b/.evergreen/scripts/setup-dev-env.sh index d9fbef2b04..a3b9b24f5b 100755 --- a/.evergreen/scripts/setup-dev-env.sh +++ b/.evergreen/scripts/setup-dev-env.sh @@ -16,7 +16,7 @@ if [ -f $HERE/test-env.sh ]; then . $HERE/test-env.sh fi -# The bin dir for the pinned uv/just. setup-system.sh sets it on evergreen hosts; +# The bin dir for uv/just. setup-system.sh sets it on evergreen hosts; # default it here so local dev (without setup-system.sh) also has a usable value. # Native (Windows) form on cygwin, like install-dependencies.sh. export PYMONGO_BIN_DIR="${PYMONGO_BIN_DIR:-$HOME/.local/bin}" diff --git a/.evergreen/scripts/setup-uv-python.sh b/.evergreen/scripts/setup-uv-python.sh index 2fe4ff5f3c..188c6a1dbb 100755 --- a/.evergreen/scripts/setup-uv-python.sh +++ b/.evergreen/scripts/setup-uv-python.sh @@ -11,7 +11,8 @@ # UV_PYTHON_PREFERENCE - "system" so the toolchain wins over managed installs. # A preference set by the task is left alone. # UV_PYTHON - the Python interpreter uv uses; defaults to CPython -# 3.11 when the task does not set one. +# 3.11, or the toolchain interpreter's path when the +# toolchain has the requested version. set -euo pipefail HERE=$(dirname "${BASH_SOURCE:-$0}") @@ -48,12 +49,17 @@ fi # uv version in pyproject.toml. export UV_PYTHON="${UV_PYTHON:-3.11}" -# Print the Python toolchain bin dir for a version like "3.11" or "3.14t". -function _toolchain_dir() { +# Print the Python toolchain bin dir for a version like "3.11" or "3.14t", +# without checking that it exists. +function _toolchain_bin_dir() { local version="$1" dir # Only plain CPython versions live in the toolchain. [[ "$version" =~ ^[0-9]+\.[0-9]+t?$ ]] || return 1 - if [ "Windows_NT" = "${OS:-}" ]; then + if [ -n "${PYMONGO_TOOLCHAIN_ROOT:-}" ]; then + # Test override of the unix toolchain root; the /bin layout under + # it is unchanged. + dir="${PYMONGO_TOOLCHAIN_ROOT}/${version}/bin" + elif [ "Windows_NT" = "${OS:-}" ]; then local winver="${version%t}" winver="${winver//./}" if [ -n "${IS_WIN32:-}" ]; then @@ -70,6 +76,25 @@ function _toolchain_dir() { else dir="/opt/python/${version}/bin" fi + echo "$dir" +} + +# Print the toolchain interpreter file for a version like "3.15t", without +# checking that it exists. Windows interpreters are exe files: native uv +# needs the exact file name. +function _interpreter_file() { + local dir="$1" version="$2" + if [ "Windows_NT" = "${OS:-}" ]; then + echo "$dir/python${version}.exe" + else + echo "$dir/python${version}" + fi +} + +# Print the toolchain bin dir for the version when it exists on this host. +function _toolchain_dir() { + local dir + dir=$(_toolchain_bin_dir "$1") || return 1 [ -d "$dir" ] || return 1 echo "$dir" } @@ -115,6 +140,15 @@ if [[ "$UV_PYTHON" == */* || "$UV_PYTHON" == *\\* ]]; then _skip_ensure=1 elif _dir=$(_toolchain_dir "$UV_PYTHON"); then _search_path="$_dir" + # Use the toolchain interpreter by explicit path when the task did not set its + # own preference (PYTHON-6135): uv uses the path as-is, so provisioning cannot + # fail on uv's interpreter discovery (it aborts on interpreters it cannot + # inspect, like RHEL8's /usr/bin/python3 3.6) or on a missing download. + _file=$(_interpreter_file "$_dir" "$UV_PYTHON") + if [ -z "${UV_PYTHON_PREFERENCE:-}" ] && [ -x "$_file" ]; then + export UV_PYTHON="$_file" + _skip_ensure=1 + fi fi # Point uv at the toolchain Python when there is one and the task did not set diff --git a/.evergreen/scripts/setup_tests.py b/.evergreen/scripts/setup_tests.py index bfa767e342..e5525a5281 100644 --- a/.evergreen/scripts/setup_tests.py +++ b/.evergreen/scripts/setup_tests.py @@ -1,6 +1,7 @@ from __future__ import annotations import base64 +import hashlib import os import platform import shutil @@ -18,6 +19,7 @@ PERF_PYTHON_VERSION, PLATFORM, ROOT, + SANITIZER_PYTHON, TEST_SUITE_MAP, Distro, check_drivers_tools, @@ -56,9 +58,22 @@ # Map the test name to test group. GROUP_MAP = dict(fuzz="fuzz", mockupdb="mockupdb", perf="perf") +# The test files run under ASan/UBSan (PYTHON-6048). They exercise the +# buffer-protocol acquisition path in bson/_cbsonmodule.c +# (_get_buffer/_prepare_input_buffer) and the wire-message builders in +# pymongo/_cmessagemodule.c (_op_msg, _batched_op_msg, +# _encode_batched_write_command). +SANITIZER_FILES = [ + "test/test_bson.py", + "test/test_raw_bson.py", + "test/test_raw_bson_shared.py", + "test/test_client.py", +] + # The libmongocrypt release used when LIBMONGOCRYPT_URL is not set. Must be at -# least 1.20.0 for the GA "substring" query type. -LIBMONGOCRYPT_VERSION = "1.20.2" +# least 1.21.0; the beta preview string query types were removed in 1.21.0 +# (MONGOCRYPT-938). +LIBMONGOCRYPT_VERSION = "1.21.0" def is_set(var: str) -> bool: @@ -71,7 +86,7 @@ def get_distro() -> Distro: version_id = "" arch = platform.machine() with open("/etc/os-release") as fid: - for line in fid.readlines(): + for line in fid: line = line.replace('"', "") # noqa: PLW2901 if line.startswith("NAME="): _, _, name = line.strip().partition("=") @@ -390,44 +405,33 @@ def handle_test_env() -> None: UV_ARGS.append("--extra zstd") if test_name in ["encryption", "kms"]: - # The "String" algorithm and the GA prefix/suffix/substring query types - # need libmongocrypt 1.19.0+, which is only exercised against MongoDB - # 9.0+. Servers before 9.0 test the preview query types instead, which - # need the "textPreview" algorithm, so pin to the released pymongocrypt - # and use the libmongocrypt bundled in its wheel rather than the - # unreleased master build. - # Evergreen exposes the server version as VERSION, not MONGODB_VERSION - # (which is only set inside the separate run_server.py process). - use_pymongocrypt_text_preview = os.environ.get("VERSION", "").startswith("8.") - - if not use_pymongocrypt_text_preview: - # Check for libmongocrypt download. - if not (ROOT / "libmongocrypt").exists(): - setup_libmongocrypt() + # The GA string query types need libmongocrypt 1.19.0+ and the beta + # preview query types were removed in 1.21.0 (PYTHON-5959), so always + # use the master pymongocrypt build against the pinned libmongocrypt + # rather than the lib bundled in the released wheel. + # Check for libmongocrypt download. + if not (ROOT / "libmongocrypt").exists(): + setup_libmongocrypt() if not opts.test_min_deps: - if use_pymongocrypt_text_preview: - UV_ARGS.append("--with pymongocrypt<1.19") - else: - UV_ARGS.append( - "--with pymongocrypt@git+https://github.com/mongodb/libmongocrypt@master#subdirectory=bindings/python" - ) - - if not use_pymongocrypt_text_preview: - # Use the nocrypto build to avoid dependency issues with older windows/python versions. - BASE = get_libmongocrypt_base() - if PLATFORM == "linux": - if (BASE / "lib/libmongocrypt.so").exists(): - PYMONGOCRYPT_LIB = BASE / "lib/libmongocrypt.so" - else: - PYMONGOCRYPT_LIB = BASE / "lib64/libmongocrypt.so" - elif PLATFORM == "darwin": - PYMONGOCRYPT_LIB = BASE / "lib/libmongocrypt.dylib" + UV_ARGS.append( + "--with pymongocrypt@git+https://github.com/mongodb/libmongocrypt@master#subdirectory=bindings/python" + ) + + # Use the nocrypto build to avoid dependency issues with older windows/python versions. + BASE = get_libmongocrypt_base() + if PLATFORM == "linux": + if (BASE / "lib/libmongocrypt.so").exists(): + PYMONGOCRYPT_LIB = BASE / "lib/libmongocrypt.so" else: - PYMONGOCRYPT_LIB = BASE / "bin/mongocrypt.dll" - if not PYMONGOCRYPT_LIB.exists(): - raise RuntimeError("Cannot find libmongocrypt shared object file") - write_env("PYMONGOCRYPT_LIB", PYMONGOCRYPT_LIB.as_posix()) + PYMONGOCRYPT_LIB = BASE / "lib64/libmongocrypt.so" + elif PLATFORM == "darwin": + PYMONGOCRYPT_LIB = BASE / "lib/libmongocrypt.dylib" + else: + PYMONGOCRYPT_LIB = BASE / "bin/mongocrypt.dll" + if not PYMONGOCRYPT_LIB.exists(): + raise RuntimeError("Cannot find libmongocrypt shared object file") + write_env("PYMONGOCRYPT_LIB", PYMONGOCRYPT_LIB.as_posix()) # PATH is updated by configure-env.sh for access to mongocryptd. if test_name == "encryption": @@ -544,8 +548,58 @@ def handle_test_env() -> None: with zipfile.ZipFile(zip_path) as zf: zf.extractall(corpus_dir) zip_path.unlink() + if sub_test_name == "fuzz": + # PYTHON-6178 Also seed from the committed corpus of previously + # captured inputs, so the nightly builds on prior discoveries + # instead of the spec seeds alone. Regression runs (PRs) keep + # running only the reproducers and the spec seed corpus. + committed_dir = ROOT / "fuzz" / "corpus" + if committed_dir.is_dir(): + for path in sorted(committed_dir.iterdir()): + if path.name.startswith("."): + continue + shutil.copyfile(path, corpus_dir / path.name) + # Manifest of every input this run starts from; capture_corpus.py + # treats these digests as already-known, so only units the fuzzer + # discovered during the run get captured. + with open(scratch_dir / "baseline.txt", "w", encoding="utf-8") as fp: + for path in sorted(corpus_dir.iterdir()): + if path.is_file(): + fp.write(hashlib.sha256(path.read_bytes()).hexdigest() + "\n") write_env("FUZZ_CORPUS_DIR", str(corpus_dir)) + if test_name == "sanitizer": + if PLATFORM != "linux": + raise RuntimeError("The sanitizer tests require the Linux Python toolchain.") + if not Path(SANITIZER_PYTHON).is_file(): + raise RuntimeError( + f"Sanitizer interpreter not found at {SANITIZER_PYTHON}; " + "the task must run on a host with the ASan/UBSan toolchain Python." + ) + # Clear stale C artifacts: build_ext reuses them by mtime, and a + # plain same-version CPython build shares the ABI tag. + shutil.rmtree(ROOT / "build", ignore_errors=True) + for pkg in ["bson", "pymongo"]: + for ext in (ROOT / pkg).glob("*.so"): + ext.unlink() + # Build and run against the ASan/UBSan-instrumented toolchain CPython, + # and fail loudly rather than silently skip the C extension build. + write_env("UV_PYTHON", SANITIZER_PYTHON) + write_env("PYMONGO_C_EXT_MUST_BUILD") + write_env("CFLAGS", "-fsanitize=address,undefined -fno-omit-frame-pointer -g -O1") + write_env("LDFLAGS", "-fsanitize=address,undefined") + # CPython's pymalloc trips LeakSanitizer with false positives. + write_env("ASAN_OPTIONS", "detect_leaks=0") + # UBSan only warns by default; make undefined behavior fail the task. + write_env("UBSAN_OPTIONS", "halt_on_error=1:print_stacktrace=1") + # The toolchain interpreter self-initializes the sanitizer runtimes, + # so no LD_PRELOAD: gcc's libasan.so is a linker script that ld.so + # cannot preload, and preloading a mismatched runtime would mix two + # sanitizers in one process. + # -s: with halt_on_error=1, a sanitizer failure exits the interpreter + # before pytest replays captured stderr, losing the report and trace. + TEST_ARGS = "-s " + " ".join(SANITIZER_FILES) + " " + TEST_ARGS + # Add coverage if requested. if opts.cov: # Keep in sync with combine-coverage.sh. diff --git a/.evergreen/scripts/setup-uv.py b/.evergreen/scripts/setup_uv.py similarity index 61% rename from .evergreen/scripts/setup-uv.py rename to .evergreen/scripts/setup_uv.py index f26b8b180c..76d0d4e9b1 100755 --- a/.evergreen/scripts/setup-uv.py +++ b/.evergreen/scripts/setup_uv.py @@ -1,13 +1,20 @@ #!/usr/bin/env python3 -"""Bootstrap the pinned uv/just for the test environment. +"""Bootstrap uv/just for the test environment. -install-dependencies.sh probes with `setup-uv.py --check`, sources ensure-uv.sh +install-dependencies.sh probes with `setup_uv.py --check`, sources ensure-uv.sh (which finds or installs uv), then runs this script for the rest. Only the standard library is used. +The project always controls a uv in UV_TOOL_BIN_DIR: the pinned version when +[tool.uv] required-version is set, the latest uv otherwise. A uv found +elsewhere on PATH may be invisible to later steps, so setup never accepts it +as-is. + This runs under the host's system python3, which may be older than our minimum supported version. """ +from __future__ import annotations + import os import re import shlex @@ -24,7 +31,7 @@ def required_uv_pin() -> str: - """Return [tool.uv] required-version, e.g. '==0.12.12' ('' if absent).""" + """Return [tool.uv] required-version, e.g. '==1.2.3' ('' if absent).""" pattern = re.compile(r"required-version\s*=\s*['\"]?([^'\"\s]+)['\"]?") in_uv = False for line in (ROOT / "pyproject.toml").read_text().splitlines(): @@ -63,21 +70,25 @@ def _install_uv_astral() -> None: _add_path(os.environ["UV_TOOL_BIN_DIR"]) -def _pin_uv(uv_pin: str) -> None: - """Install the pinned uv via uv tool install --force. +def _uv_exe() -> str: + """The uv binary name on this platform.""" + return "uv.exe" if os.name == "nt" else "uv" + - UV_TOOL_BIN_DIR and UV_TOOL_DIR are inherited from the environment (set by - install-dependencies.sh / ensure-uv.sh, in native form on Windows). uv tool - install writes the binary into UV_TOOL_BIN_DIR and the tool venv into - UV_TOOL_DIR; --force lets it overwrite an existing install. +def _install_uv(pin: str) -> None: + """Install uv into UV_TOOL_BIN_DIR with `uv tool install --force`. - Windows will not overwrite a running executable, so when the current uv is - already the target bin dir, run the install from a copy of the binary. + Installs the pinned version when pin is set ("==0.12.12"), the latest uv + otherwise (pin ""). Windows will not overwrite a running executable, so + when the uv driving the install is the binary being replaced, run the + install from a copy of it. """ uv_path = shutil.which("uv") + bin_dir = os.environ["UV_TOOL_BIN_DIR"] + overwrite_self = uv_path is not None and _same_path(uv_path, str(Path(bin_dir, _uv_exe()))) tool = uv_path tmp_uv = None - if os.name == "nt": + if overwrite_self: tmp_uv = Path(tempfile.mkdtemp()) / Path(uv_path).name shutil.copy2(uv_path, tmp_uv) tool = str(tmp_uv) @@ -91,7 +102,7 @@ def _pin_uv(uv_pin: str) -> None: "-q", "--force", "--from", - f"uv{uv_pin}", + f"uv{pin}", "uv", ], check=True, @@ -131,9 +142,51 @@ def _write_env() -> None: ENV_SH.write_bytes(("\n".join(keep) + "\n").encode()) -def _pinned_uv_installed() -> bool: - """Return True when the uv on PATH already matches the required-version pin.""" +def _cygdrive(path: str) -> str: + """Map a native Windows path to its cygwin /cygdrive form.""" + match = re.match(r"^([A-Za-z]):[/\\](.*)$", path) + if not match: + return path + drive, rest = match.groups() + return "/cygdrive/" + drive.lower() + "/" + rest.replace("\\", "/") + + +def _same_path(a: str, b: str) -> bool: + """Compare two paths, tolerating forms realpath cannot unify. + + On cygwin, which() may report a /cygdrive form while UV_TOOL_BIN_DIR is + native ("C:/..."). + """ + try: + if os.path.realpath(a) == os.path.realpath(b): + return True + except OSError: + pass + return any( + os.path.normcase(os.path.normpath(form_a)) == os.path.normcase(os.path.normpath(form_b)) + for form_a in (a, _cygdrive(a)) + for form_b in (b, _cygdrive(b)) + ) + + +def _project_uv_installed() -> bool: + """Return True when the uv on PATH is the one this setup put in UV_TOOL_BIN_DIR.""" + uv_path = shutil.which("uv") + bin_dir = os.environ.get("UV_TOOL_BIN_DIR") + if not uv_path or not bin_dir: + return False + return _same_path(uv_path, str(Path(bin_dir, _uv_exe()))) + + +def _required_uv_installed() -> bool: + """Return True when the uv on PATH already satisfies the setup requirement. + + With a required-version pin, the uv on PATH must match it exactly; without + a pin, it must be the project-controlled uv in UV_TOOL_BIN_DIR. + """ pin = required_uv_pin() + if not pin: + return _project_uv_installed() if not pin.startswith("=="): # Only exact pins are checked here; anything else falls back to setup. return False @@ -152,7 +205,7 @@ def main() -> int: # there would download Python and install dependencies just to decide # whether setup is needed. if "--check" in sys.argv[1:]: - return 0 if _pinned_uv_installed() else 1 + return 0 if _required_uv_installed() else 1 bin_dir = os.environ["UV_TOOL_BIN_DIR"] Path(bin_dir).mkdir(parents=True, exist_ok=True) @@ -164,7 +217,14 @@ def main() -> int: uv_pin = required_uv_pin() if uv_pin: - _pin_uv(uv_pin) + _install_uv(uv_pin) + elif not _project_uv_installed(): + # Unpinned: still install the latest uv into UV_TOOL_BIN_DIR, so the + # project controls the uv that later steps find on PATH. A uv found + # elsewhere (the vendored submodule's, the host's) may be missing from + # those steps' PATH entirely, and may lack behavior the project relies + # on, such as provisioning newer CPythons. + _install_uv("") _write_env() return 0 diff --git a/.evergreen/scripts/test_generate_config.py b/.evergreen/scripts/test_generate_config.py index f078f2f305..8d299054ff 100644 --- a/.evergreen/scripts/test_generate_config.py +++ b/.evergreen/scripts/test_generate_config.py @@ -46,7 +46,8 @@ def all_variants(): def variant_selects(variant, task): """Whether the variant's task selectors match the task: "." selects a - tag, "!" negates the token that follows, a bare token names a task.""" + tag, "!" negates the token that follows, a bare token names a task. + """ tags = task.tags or [] for ref in variant.tasks: includes, excludes, names = [], [], [] @@ -75,7 +76,8 @@ def variant_selects(variant, task): def test_pr_tasks_pin_max_version(): """Task-level pins: pr tasks pin MAX_VERSION (the "latest" nightly is unstable); the explicit 4.4 min-deps pin is the exception. Variant-merged - pins are checked by test_pr_tasks_effectively_pin_max_version.""" + pins are checked by test_pr_tasks_effectively_pin_max_version. + """ offenders = [ (task.name, task_vars(task).get("VERSION")) for task in pr_tasks() @@ -91,7 +93,8 @@ def test_pr_tasks_effectively_pin_max_version(): """Effective pins: a pr task without its own VERSION var inherits the selecting variant's version, so every pr task that runs a server must resolve to MAX_VERSION once variant expansions merge in. The explicit - 4.4 min-deps pin is the exception.""" + 4.4 min-deps pin is the exception. + """ tasks = [task for task in all_tasks() if "pr" in (task.tags or [])] offenders = [] for variant in all_variants(): @@ -112,17 +115,22 @@ def test_pr_tasks_effectively_pin_max_version(): def test_server_version_pr_tasks_selected_once(): - """The mongodb-* variants differ only in server version, so a pr task - must be selected only by the variant running the server version it pins.""" + """A pr server-version task must be selected only by the variant running + the server version it pins. The expected family comes from + create_server_version_variants(), not from the selections: a variant + missing its PR selector would otherwise drop from both sides and the + comparison would pass. Variants outside the family must not select these + tasks (the sanitizer variant pins MAX_VERSION for its own mongod). + """ + sv_tasks = [task for task in pr_tasks() if "server-version" in (task.tags or [])] + sv_variants = generate_config.create_server_version_variants() offenders = {} - for task in pr_tasks(): - if "server-version" not in (task.tags or []): - continue + for task in sv_tasks: own = task_vars(task).get("VERSION") selecting = [variant.name for variant in all_variants() if variant_selects(variant, task)] matching = [ variant.name - for variant in all_variants() + for variant in sv_variants if (variant.expansions or {}).get("VERSION") == own ] if selecting != matching: @@ -134,7 +142,8 @@ def test_server_version_pr_tasks_selected_once(): def test_pr_tasks_cover_version_boundaries(): """PRs test the server version boundaries: the newest numbered server - with every Python boundary, the min server with its min-Python floor.""" + with every Python boundary, the min server with its min-Python floor. + """ for version, pythons in ( ( generate_config_utils.MAX_VERSION, @@ -156,7 +165,8 @@ def test_pr_tasks_cover_version_boundaries(): def test_server_version_rotated_tasks_keep_coverage(): """Per-commit coverage for this family rides the rotated boundary-Python - tasks, not the pr tasks (which run only on MAX_VERSION).""" + tasks, not the pr tasks (which run only on MAX_VERSION). + """ family = [task for task in all_tasks() if "server-version" in (task.tags or [])] cov = [task for task in family if task_vars(task).get("COVERAGE") == "1"] assert any("pr" not in (task.tags or []) for task in cov), ( @@ -190,7 +200,8 @@ def test_pr_min_deps_tasks_also_run_coverage(): def test_standard_family_pr_budget(): """Patch-build PR budget: at most 5 pr-tagged test-standard tasks (the pre-pin baseline), at most 3 on Python 3.14+ (the ubuntu22 compression - filter).""" + filter). + """ tasks = [task for task in pr_tasks() if "test-standard" in (task.tags or [])] assert len(tasks) <= 5, f"too many test-standard PR tasks: {[t.name for t in tasks]}" newer = [ @@ -206,7 +217,8 @@ def test_standard_family_pr_budget(): def test_pr_tasks_run_coverage(): """Pr tasks that pin a server version run with COVERAGE=1; no-cov - companions and infrastructure tasks (no VERSION) are exempt.""" + companions and infrastructure tasks (no VERSION) are exempt. + """ offenders = [ task.name for task in pr_tasks() @@ -220,7 +232,8 @@ def test_pr_tasks_run_coverage(): def test_rotated_tasks_keep_nightly_coverage(): """Batch coverage rides the rotation independently of the pr tasks: rotated "latest" tasks and max-Python auth-aws tasks keep COVERAGE=1 - (min-deps excepted).""" + (min-deps excepted). + """ offenders = [] for task in all_tasks(): tags = task.tags or [] @@ -268,7 +281,8 @@ def test_rotated_tasks_keep_nightly_coverage(): def test_non_standard_cov_tasks_have_no_cov_companions(): """Each non-standard coverage task also emits a no-cov companion, so the macOS/Win64 encryption variants (which filter .cov) have a task to - activate in patch builds.""" + activate in patch builds. + """ no_cov = {task.name for task in all_tasks() if "test-non-standard-no-cov" in (task.tags or [])} for task in all_tasks(): if "test-non-standard-no-cov" in (task.tags or []): @@ -276,3 +290,76 @@ def test_non_standard_cov_tasks_have_no_cov_companions(): elif "cov" in (task.tags or []) and "test-non-standard" in (task.tags or []): companion = task.name.removesuffix("-cov") assert companion in no_cov, f"missing no-cov companion for {task.name}" + + +def test_fuzz_task_wiring(): + """Two fuzz variants: the pr-tagged regression variant runs the + reproducers on every PR; the nightly variant (which also captures the + corpus) carries no "pr" tag, so PR patch builds never select it, while + its default patchability keeps it manually runnable + (`evergreen patch --variant fuzz-rhel8 --task fuzz`). + """ + tasks = [task for task in all_tasks() if "fuzz" in (task.tags or [])] + assert [task.name for task in tasks if "pr" in (task.tags or [])] == ["fuzz-regression"] + assert [task.name for task in tasks if "pr" not in (task.tags or [])] == ["fuzz"] + variants = generate_config.create_fuzz_variants() + assert len(variants) == 2 + regression, nightly = variants + assert variant_selects(regression, tasks[0]) + assert "pr" in (regression.tags or []) + assert variant_selects(nightly, tasks[1]) + assert nightly.batchtime == generate_config_utils.BATCHTIME_DAY + # Webhook PR patch builds only select pr-tagged variants. + assert not nightly.tags + # The capture subprocess bootstraps the comment-bot github app, whose + # secrets live in AWS Secrets Manager: it needs the assumed-role + # credentials (as resync_specs and backport-pr also pass them). + capture = tasks[1].commands[-1] + env_vars = capture.params["include_expansions_in_env"] + for var in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN"): + assert var in env_vars, f"capture subprocess missing {var}" + # The capture no longer keys off is_patch: manual patch runs must + # capture too, and the nightly variant never runs in a PR build. + assert "is_patch" not in env_vars + + +def test_load_balancer_marker_selection(monkeypatch): + """The load balancer tasks select the load_balancer marker explicitly: + pytest_conf.py only grants the implicit default markers to unmarked + tests, so the marker expression must add the full default suite + alongside the load balancer tests (PYTHON-6262). + """ + import run_tests + + monkeypatch.setattr(run_tests, "TEST_NAME", "load_balancer") + monkeypatch.setattr(run_tests, "GREEN_FRAMEWORK", None) + monkeypatch.setattr(run_tests, "TEST_ARGS", ["-m", "load_balancer"]) + run_tests.handle_load_balancer_marker() + assert run_tests.TEST_ARGS[-2:] == [ + "-m", + "default or default_async or load_balancer", + ] + + +def test_sanitizer_task_wiring(): + """PYTHON-6048: one pr-tagged sanitizer task, selected by exactly one + variant that pins MAX_VERSION and runs on a large host for ASan's memory + headroom. VERSION stays off the task so it is exempt + from the pr COVERAGE rule (coverage under ASan is not useful). + """ + tasks = [task for task in all_tasks() if "sanitizer" in (task.tags or [])] + assert len(tasks) == 1 + task = tasks[0] + assert "pr" in task.tags + funcs = [getattr(cmd, "func", None) for cmd in task.commands] + assert funcs == ["run server", "run tests"] + vars_ = task_vars(task) + assert vars_["TEST_NAME"] == "sanitizer" + assert vars_["TOPOLOGY"] == "standalone" + assert vars_["AUTH"] == "noauth" + assert vars_["SSL"] == "nossl" + assert "VERSION" not in vars_ + variants = [v for v in all_variants() if variant_selects(v, task)] + assert len(variants) == 1 + assert variants[0].run_on == ["rhel8.10-large"] + assert (variants[0].expansions or {}).get("VERSION") == generate_config_utils.MAX_VERSION diff --git a/.evergreen/scripts/test_setup_uv.py b/.evergreen/scripts/test_setup_uv.py new file mode 100644 index 0000000000..1fd49a4bb2 --- /dev/null +++ b/.evergreen/scripts/test_setup_uv.py @@ -0,0 +1,522 @@ +"""Tests for .evergreen/scripts/setup_uv.py and .evergreen/scripts/setup-uv-python.sh. + +Run with: python -m pytest .evergreen/scripts/test_setup_uv.py + +The bash tests drive setup-uv-python.sh with a stub `uv` whose `python find` / +`python install` fail the way CI's uv does on hosts like rhel8.10 (an +un-inspectable /usr/bin/python3 and no cpython-3.15 download), plus a fake +toolchain root selected through PYMONGO_TOOLCHAIN_ROOT. +""" + +from __future__ import annotations + +import importlib.util +import os +import shutil +import stat +import subprocess +import sys +from pathlib import Path + +import pytest + +# The repo's pytest addopts deselect modules without the "default" mark. +pytestmark = [ + pytest.mark.default, + pytest.mark.skipif( + sys.platform in ("win32", "cygwin") or shutil.which("bash") is None, + reason="needs a unix shell", + ), +] + +HERE = Path(__file__).resolve().parent +SETUP_UV = HERE / "setup_uv.py" +SETUP_UV_PYTHON_SH = HERE / "setup-uv-python.sh" + +PIN = "==0.12.12" + +UNPINNED_PYPROJECT = '[project]\nname = "test"\n' +PINNED_PYPROJECT = f'[project]\nname = "test"\n\n[tool.uv]\nrequired-version = "{PIN}"\n' + +# A stub `uv` that fails `python find`/`python install` the way CI's uv does +# on rhel8.10, records each invocation to $UV_STUB_LOG, and emulates +# `uv tool install` by copying itself into $UV_TOOL_BIN_DIR. +STUB_UV = """\ +#!/bin/bash +[ -n "${UV_STUB_LOG:-}" ] && printf '%s\\n' "$*" >> "$UV_STUB_LOG" +case "${1:-}" in + --version|version) + printf 'uv %s (x86_64-unknown-linux-gnu)\\n' "${UV_STUB_VERSION:-0.12.24}" + exit 0 ;; +esac +case "$1 $2" in + "python find") + if [ "${3:-}" = ">=3.9" ] && [ -n "${UV_STUB_FALLBACK:-}" ]; then + printf '%s\\n' "$UV_STUB_FALLBACK" + exit 0 + fi + printf 'error: Failed to inspect Python interpreter from search path at `/usr/bin/python3`\\n' >&2 + exit 1 ;; + "python install") + printf 'error: No download found for request: cpython-3.15-linux-x86_64-gnu\\n' >&2 + exit 1 ;; + "tool install") + req="" + prev="" + for arg in "$@"; do + if [ "$prev" = "--from" ]; then req="$arg"; fi + prev="$arg" + done + [ -n "${UV_STUB_LOG:-}" ] && printf 'installed-from=%s\\n' "$req" >> "$UV_STUB_LOG" + mkdir -p "${UV_TOOL_BIN_DIR:?}" + cp "$0" "${UV_TOOL_BIN_DIR}/uv" + exit 0 ;; +esac +printf 'stub uv: unhandled invocation: %s\\n' "$*" >&2 +exit 64 +""" + + +def make_executable(path: Path) -> Path: + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + return path + + +def write_stub_uv(bin_dir: Path) -> Path: + bin_dir.mkdir(parents=True, exist_ok=True) + stub = bin_dir / "uv" + stub.write_text(STUB_UV) + return make_executable(stub) + + +def make_toolchain(root: Path, version: str) -> Path: + """Create a fake toolchain interpreter, e.g. /3.15/bin/python3.15.""" + interpreter = root / version / "bin" / f"python{version}" + interpreter.parent.mkdir(parents=True, exist_ok=True) + interpreter.write_text("#!/bin/sh\nexit 0\n") + return make_executable(interpreter) + + +def make_sentinel(root: Path) -> Path: + """Create a no-op executable, used as an interpreter path the script accepts.""" + sentinel = root / "sentinel" + sentinel.write_text("#!/bin/sh\nexit 0\n") + return make_executable(sentinel) + + +def stub_calls(log: Path) -> list[str]: + if not log.exists(): + return [] + return [line for line in log.read_text().splitlines() if not line.startswith("installed-from=")] + + +# --- setup-uv-python.sh ------------------------------------------------------ + +setup_uv = importlib.util.module_from_spec( + importlib.util.spec_from_file_location("setup_uv", HERE / "setup_uv.py") +) +setup_uv.__spec__.loader.exec_module(setup_uv) + + +def call_toolchain_bin_dir(script_copy: Path, version: str, env_overrides: dict) -> str: + """Call the script's _toolchain_bin_dir helper and return the printed path.""" + proc = subprocess.run( # noqa: S603 + ["/bin/bash", "-c", f'. "{script_copy}"; _toolchain_bin_dir "{version}"'], + check=False, + env={ + "PATH": "/usr/bin:/bin", + "HOME": str(script_copy.parents[2]), + **env_overrides, + }, + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stderr + return proc.stdout.strip() + + +def script_copy_in(tmp_path: Path) -> Path: + """Copy setup-uv-python.sh into a temporary project tree and return its path.""" + scripts = tmp_path / "proj" / ".evergreen" / "scripts" + scripts.mkdir(parents=True) + script_copy = scripts / "setup-uv-python.sh" + shutil.copy(SETUP_UV_PYTHON_SH, script_copy) + return script_copy + + +def run_setup_uv_python( + tmp_path: Path, extra_env: dict, cwd: Path | None = None +) -> subprocess.CompletedProcess: + """Source a copy of setup-uv-python.sh in a temporary project tree. + + The copy's HERE/ROOT resolve inside the tree, so the script sources the + tree's env.sh (if any) and probes the tree's .venv, never the checkout's. + Reports rc and the exported UV_PYTHON / search path / preference. + """ + script_copy = script_copy_in(tmp_path) + env = { + "HOME": str(tmp_path), + "CI": "true", + } + env.update(extra_env) + return subprocess.run( # noqa: S603 + [ + "/bin/bash", + "-c", + ( + f'. "{script_copy}"; ' + 'printf "\\nUV_PYTHON=%s" "$UV_PYTHON"; ' + 'printf "\\nSEARCH_PATH=%s" "${UV_PYTHON_SEARCH_PATH-}"; ' + 'printf "\\nPREFERENCE=%s" "${UV_PYTHON_PREFERENCE-}"; ' + 'printf "\\nTOOL_BIN_DIR=%s" "${UV_TOOL_BIN_DIR-}"' + ), + ], + check=False, + env=env, + cwd=str(cwd or tmp_path), + capture_output=True, + text=True, + ) + + +@pytest.fixture +def stub_env(tmp_path): + """A stub uv bin dir and its invocation log; returns (log, env-overrides).""" + log = tmp_path / "uv-stub.log" + write_stub_uv(tmp_path / "stub-bin") + return log, {"PATH": f"{tmp_path / 'stub-bin'}:/usr/bin:/bin", "UV_STUB_LOG": str(log)} + + +def test_toolchain_python_is_used_by_path(tmp_path, stub_env): + """CI: an exact toolchain match wins by explicit path, without uv find/install.""" + log, env = stub_env + interpreter = make_toolchain(tmp_path / "toolchain", "3.15") + proc = run_setup_uv_python( + tmp_path, + extra_env={ + **env, + "UV_PYTHON": "3.15", + "PYMONGO_TOOLCHAIN_ROOT": str(tmp_path / "toolchain"), + }, + ) + assert proc.returncode == 0, proc.stderr + assert f"UV_PYTHON={interpreter}" in proc.stdout + assert f"SEARCH_PATH={interpreter.parent}" in proc.stdout + assert "PREFERENCE=system" in proc.stdout + assert stub_calls(log) == [] + + +def test_toolchain_falls_through_when_interpreter_missing(tmp_path, stub_env): + """CI: a toolchain dir without the requested version keeps using uv find/install.""" + log, env = stub_env + make_toolchain(tmp_path / "toolchain", "3.14") + proc = run_setup_uv_python( + tmp_path, + extra_env={ + **env, + "UV_PYTHON": "3.15", + "PYMONGO_TOOLCHAIN_ROOT": str(tmp_path / "toolchain"), + }, + ) + assert proc.returncode == 1 + assert "could not find or install Python" in proc.stderr + assert stub_calls(log) == ["python find 3.15", "python install 3.15"] + + +def test_task_preference_disables_bypass(tmp_path, stub_env): + """A task-set UV_PYTHON_PREFERENCE (PYTHON-6135) keeps the pre-bypass behavior.""" + log, env = stub_env + make_toolchain(tmp_path / "toolchain", "3.15") + proc = run_setup_uv_python( + tmp_path, + extra_env={ + **env, + "UV_PYTHON": "3.15", + "UV_PYTHON_PREFERENCE": "only-managed", + "PYMONGO_TOOLCHAIN_ROOT": str(tmp_path / "toolchain"), + }, + ) + assert proc.returncode == 1 + assert "could not find or install Python" in proc.stderr + # rc 1 means the explicit-path branch did not run. + assert stub_calls(log) == ["python find 3.15", "python install 3.15"] + + +def test_local_fallback_without_toolchain(tmp_path, stub_env): + """Local (no CI) hosts fall back to any interpreter >=3.9 when find/install fail.""" + _, env = stub_env + fallback = make_toolchain(tmp_path / "elsewhere", "3.11") + proc = run_setup_uv_python( + tmp_path, + extra_env={ + **env, + "UV_PYTHON": "3.15", + "CI": "", + "UV_STUB_FALLBACK": str(fallback), + # An empty toolchain root: no version can match it. + "PYMONGO_TOOLCHAIN_ROOT": str(tmp_path / "no-toolchain"), + }, + ) + assert proc.returncode == 0, proc.stderr + assert f"UV_PYTHON={fallback}" in proc.stdout + + +def test_explicit_interpreter_path_skips_probing(tmp_path, stub_env): + """An explicit interpreter path in UV_PYTHON is used as-is.""" + log, env = stub_env + interpreter = make_toolchain(tmp_path / "elsewhere", "3.12") + proc = run_setup_uv_python(tmp_path, extra_env={**env, "UV_PYTHON": str(interpreter)}) + assert proc.returncode == 0, proc.stderr + assert f"UV_PYTHON={interpreter}" in proc.stdout + assert stub_calls(log) == [] + + +def test_toolchain_paths_preserved_without_override(tmp_path): + """Without the test override, the platform toolchain paths are preserved as-is.""" + script_copy = script_copy_in(tmp_path) + sentinel = make_sentinel(tmp_path) + if sys.platform == "darwin": + expected = { + "3.15": "/Library/Frameworks/Python.Framework/Versions/3.15/bin", + "3.15t": "/Library/Frameworks/PythonT.Framework/Versions/3.15/bin", + } + else: + expected = { + "3.15": "/opt/python/3.15/bin", + "3.15t": "/opt/python/3.15t/bin", + } + for version, path in expected.items(): + assert call_toolchain_bin_dir(script_copy, version, {"UV_PYTHON": str(sentinel)}) == path + + +def test_toolchain_override_keeps_version_layout(tmp_path): + """With the test override, the /bin layout under it is kept.""" + script_copy = script_copy_in(tmp_path) + sentinel = make_sentinel(tmp_path) + override = {"UV_PYTHON": str(sentinel), "PYMONGO_TOOLCHAIN_ROOT": str(tmp_path / "root")} + assert call_toolchain_bin_dir(script_copy, "3.15t", override) == str( + tmp_path / "root" / "3.15t" / "bin" + ) + + +def test_toolchain_branch_for_windows(tmp_path): + """The Windows branch computes the python toolchain path.""" + script_copy = script_copy_in(tmp_path) + sentinel = make_sentinel(tmp_path) + env = {"OS": "Windows_NT", "UV_PYTHON": str(sentinel)} + assert call_toolchain_bin_dir(script_copy, "3.15", env) == "C:/python/Python315" + + +def call_interpreter_file(script_copy: Path, version: str, env_overrides: dict) -> str: + """Call the script's _interpreter_file helper and return the printed path.""" + proc = subprocess.run( # noqa: S603 + [ + "/bin/bash", + "-c", + f'. "{script_copy}"; _interpreter_file "/toolchain/dir" "{version}"', + ], + check=False, + env={ + "PATH": "/usr/bin:/bin", + "HOME": str(script_copy.parents[2]), + **env_overrides, + }, + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stderr + return proc.stdout.strip() + + +def test_interpreter_file_names_the_exact_file(tmp_path): + """Windows interpreters are exe files; the other platforms use the bare name. + + Native uv needs the exact file name; cygwin bash's -x test also matches + the bare name (PYTHON-6273). + """ + script_copy = script_copy_in(tmp_path) + sentinel = make_sentinel(tmp_path) + windows = {"OS": "Windows_NT", "UV_PYTHON": str(sentinel)} + assert call_interpreter_file(script_copy, "3.15t", windows) == "/toolchain/dir/python3.15t.exe" + assert call_interpreter_file(script_copy, "3.15t", {"UV_PYTHON": str(sentinel)}) == ( + "/toolchain/dir/python3.15t" + ) + assert call_interpreter_file(script_copy, "3.11", windows) == "/toolchain/dir/python3.11.exe" + + +def test_windows_toolchain_interpreter_is_exported_as_exe_file(tmp_path, stub_env): + """CI (Windows): the exported interpreter path names the .exe file exactly. + + The script computes the toolchain dir as the native path + "C:/python/Python315", which resolves under this test's cwd. + """ + log, env = stub_env + python_dir = tmp_path / "C:" / "python" / "Python315" + python_dir.mkdir(parents=True) + interpreter = python_dir / "python3.15t.exe" + interpreter.write_text("#!/bin/sh\nexit 0\n") + make_executable(interpreter) + proc = run_setup_uv_python( + tmp_path, + extra_env={**env, "UV_PYTHON": "3.15t", "OS": "Windows_NT"}, + cwd=tmp_path, + ) + assert proc.returncode == 0, proc.stderr + assert "UV_PYTHON=C:/python/Python315/python3.15t.exe" in proc.stdout + assert stub_calls(log) == [] + + +def test_script_sources_env_sh_from_its_tree(tmp_path, stub_env): + """The script sources env.sh from the copy's tree, not the checkout's.""" + _, env = stub_env + fallback = make_toolchain(tmp_path / "elsewhere", "3.11") + proc = run_setup_uv_python( + tmp_path, + extra_env={ + **env, + "CI": "", + "UV_STUB_FALLBACK": str(fallback), + }, + ) + # A leaked checkout env.sh would set UV_TOOL_BIN_DIR; the runner tree has none. + assert proc.returncode == 0, proc.stderr + assert proc.stdout.rstrip("\n").endswith("TOOL_BIN_DIR=") + + +def test_same_path_maps_cygwin_forms(): + """A native Windows path matches its cygwin /cygdrive form.""" + assert setup_uv._same_path("C:/tools/uv.exe", "C:/tools/uv.exe") + assert setup_uv._same_path("C:/tools/uv.exe", "/cygdrive/c/tools/uv.exe") + assert setup_uv._same_path("/cygdrive/c/tools/uv.exe", "C:/tools/uv.exe") + assert not setup_uv._same_path("C:/tools/uv.exe", "C:/elsewhere/uv.exe") + + +# --- setup_uv.py ------------------------------------------------------------ + + +@pytest.fixture +def project(tmp_path): + """A fake project tree: a pyproject.toml plus a copy of setup_uv.py.""" + proj = tmp_path / "proj" + scripts = proj / ".evergreen" / "scripts" + scripts.mkdir(parents=True) + shutil.copy(SETUP_UV, scripts / "setup_uv.py") + (proj / "pyproject.toml").write_text(UNPINNED_PYPROJECT) + return proj + + +def run_setup_uv(project: Path, args: list[str], env: dict) -> subprocess.CompletedProcess: + """Run setup_uv.py with the inherited environment plus the overrides. + + Unlike the bash harness, the environment is inherited: setup_uv.py runs + subprocesses (uv tool install) that need a working PATH. + """ + return subprocess.run( # noqa: S603 + [sys.executable, str(project / ".evergreen" / "scripts" / "setup_uv.py"), *args], + check=False, + env={**os.environ, **env}, + capture_output=True, + text=True, + ) + + +def test_check_unpinned_requires_project_uv(tmp_path, project): + """Unpinned --check passes only for the uv setup installed, not any uv on PATH.""" + bin_dir = tmp_path / "project-bin" + foreign = write_stub_uv(tmp_path / "foreign-bin") + bin_dir.mkdir() + write_stub_uv(bin_dir) + env = {"PATH": f"{foreign.parent}:{bin_dir}:/usr/bin:/bin", "UV_TOOL_BIN_DIR": str(bin_dir)} + assert run_setup_uv(project, ["--check"], env).returncode == 1 + + +def test_check_unpinned_accepts_project_uv(tmp_path, project): + """Unpinned --check passes when the uv on PATH is the project-installed one.""" + bin_dir = tmp_path / "project-bin" + bin_dir.mkdir() + write_stub_uv(bin_dir) + env = {"PATH": f"{bin_dir}:/usr/bin:/bin", "UV_TOOL_BIN_DIR": str(bin_dir)} + assert run_setup_uv(project, ["--check"], env).returncode == 0 + + +def test_check_pinned_requires_exact_version(tmp_path, project): + """Pinned --check keeps comparing the uv on PATH with the pin.""" + (project / "pyproject.toml").write_text(PINNED_PYPROJECT) + bin_dir = tmp_path / "project-bin" + bin_dir.mkdir() + write_stub_uv(bin_dir) + env = { + "PATH": f"{bin_dir}:/usr/bin:/bin", + "UV_TOOL_BIN_DIR": str(bin_dir), + "UV_STUB_VERSION": "0.12.24", + } + assert run_setup_uv(project, ["--check"], env).returncode == 1 + env["UV_STUB_VERSION"] = "0.12.12" + assert run_setup_uv(project, ["--check"], env).returncode == 0 + + +def test_main_unpinned_installs_latest_uv_into_bin_dir(tmp_path, project): + """Unpinned setup installs the latest uv into UV_TOOL_BIN_DIR over a foreign uv on PATH.""" + log = tmp_path / "log" + foreign = write_stub_uv(tmp_path / "foreign-bin") + bin_dir = tmp_path / "project-bin" + env = { + "PATH": f"{foreign.parent}:/usr/bin:/bin", + "UV_TOOL_BIN_DIR": str(bin_dir), + "UV_STUB_LOG": str(log), + } + proc = run_setup_uv(project, [], env) + assert proc.returncode == 0, proc.stderr + assert (bin_dir / "uv").exists() + assert "installed-from=uv\n" in log.read_text() + + +def test_main_unpinned_skips_install_when_project_uv_on_path(tmp_path, project): + """Unpinned setup does not reinstall when the project uv is already on PATH.""" + log = tmp_path / "log" + bin_dir = tmp_path / "project-bin" + write_stub_uv(bin_dir) + env = { + "PATH": f"{bin_dir}:/usr/bin:/bin", + "UV_TOOL_BIN_DIR": str(bin_dir), + "UV_STUB_LOG": str(log), + } + proc = run_setup_uv(project, [], env) + assert proc.returncode == 0, proc.stderr + assert not log.exists() or "installed-from=" not in log.read_text() + + +def test_main_pinned_installs_pinned_uv(tmp_path, project): + """Pinned setup keeps installing the pinned uv into UV_TOOL_BIN_DIR.""" + (project / "pyproject.toml").write_text(PINNED_PYPROJECT) + log = tmp_path / "log" + foreign = write_stub_uv(tmp_path / "foreign-bin") + bin_dir = tmp_path / "project-bin" + env = { + "PATH": f"{foreign.parent}:/usr/bin:/bin", + "UV_TOOL_BIN_DIR": str(bin_dir), + "UV_STUB_LOG": str(log), + "UV_STUB_VERSION": "0.12.24", + } + proc = run_setup_uv(project, [], env) + assert proc.returncode == 0, proc.stderr + assert (bin_dir / "uv").exists() + assert f"installed-from=uv{PIN}\n" in log.read_text() + + +def test_main_pinned_self_overwrite_runs_from_copy(tmp_path, project): + """When the driving uv is the binary being replaced, the install runs from a copy.""" + (project / "pyproject.toml").write_text(PINNED_PYPROJECT) + log = tmp_path / "log" + bin_dir = tmp_path / "project-bin" + write_stub_uv(bin_dir) + env = { + "PATH": f"{bin_dir}:/usr/bin:/bin", + "UV_TOOL_BIN_DIR": str(bin_dir), + "UV_STUB_LOG": str(log), + "UV_STUB_VERSION": "0.12.12", + } + proc = run_setup_uv(project, [], env) + assert proc.returncode == 0, proc.stderr + assert (bin_dir / "uv").exists() + assert f"installed-from=uv{PIN}\n" in log.read_text() diff --git a/.evergreen/scripts/utils.py b/.evergreen/scripts/utils.py index 5b7da0f5a3..4126b86998 100644 --- a/.evergreen/scripts/utils.py +++ b/.evergreen/scripts/utils.py @@ -48,6 +48,7 @@ class Distro: "mockupdb": "mockupdb", "ocsp": "ocsp", "perf": "perf", + "sanitizer": "", "sfp": "sfp", "numpy": "", } @@ -89,6 +90,10 @@ class Distro: # The managed Python version used for perf tests (PYTHON-6135). PERF_PYTHON_VERSION = "3.11.9" +# The ASan/UBSan-instrumented toolchain CPython used by the sanitizer task +# (PYTHON-6048), built by mongo-python-toolchain (PYTHON-6067). Linux only. +SANITIZER_PYTHON = "/opt/python/3.14-asan-ubsan/bin/python3" + # Tests that do not use run-mongodb directly. NO_RUN_ORCHESTRATION = [ "auth_oidc", @@ -281,7 +286,7 @@ def handle_env_overrides(parser: argparse.ArgumentParser, opts: argparse.Namespa def read_env(path: Path | str) -> dict[str, str]: config = dict() with Path(path).open() as fid: - for line in fid.readlines(): + for line in fid: if "=" not in line: continue name, _, value = line.strip().partition("=") diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 93cbe53063..eac2263c9a 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -6,3 +6,7 @@ d88aaa6cfdb05599a79f60a2cbea5513f3788f6c # Enable ruff rule UP035 269a552da95439d38038f95794c5012428c07141 +# Enable ruff rules UP007 and UP045 +ce09d45acd3822235d433fde2d7f2f53ddb30dcd +# Enable ruff rule B905 +16d94e2b6ba2e11f93d344b55e9ecb237451d35f diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 6023350f5c..17f517f8b8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -38,6 +38,7 @@ if user.email and "@" in user.email and len(user.email) > 5: else: submit_button.enabled = False + # Consider: def valid_email(email): return email and "@" in email and len(email) > 5 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 8f82505fcb..c426ae42b4 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,14 +11,23 @@ updates: actions: patterns: - "*" - # Python (uv). Routine version updates are handled by the uv-lock-update - # workflow, so a limit of 0 turns off Dependabot version-update PRs here. - # Security updates are exempt from this limit and still open normally. + # Python (uv). Dependabot fully manages uv.lock: one grouped weekly pull + # request plus immediate, ungrouped security updates. Never set uv's + # exclude-newer in pyproject.toml instead: Dependabot resolves with it and + # produces pull requests that remove or downgrade packages + # (dependabot-core#14156). - package-ecosystem: "uv" directory: "/" schedule: interval: "weekly" - open-pull-requests-limit: 0 + cooldown: + default-days: 7 + allow: + - dependency-type: "all" + groups: + uv: + patterns: + - "*" # drivers-evergreen-tools submodule - package-ecosystem: "gitsubmodule" directory: "/" diff --git a/.github/workflows/dist.yml b/.github/workflows/dist.yml index cf99af2b9d..ca87b82c72 100644 --- a/.github/workflows/dist.yml +++ b/.github/workflows/dist.yml @@ -38,11 +38,11 @@ jobs: - [ubuntu-latest, "manylinux_aarch64", "cp3*-manylinux_aarch64"] - [ubuntu-latest, "manylinux_ppc64le", "cp3*-manylinux_ppc64le"] - [ubuntu-latest, "manylinux_s390x", "cp3*-manylinux_s390x"] - - [ubuntu-latest, "manylinux_i686", "cp3*-manylinux_i686"] + - [ubuntu-24.04, "manylinux_i686", "cp3*-manylinux_i686"] # ubuntu-latest blocks the legacy DNS calls that i686 uses - [windows-2022, "win_amd6", "cp3*-win_amd64"] - [windows-2022, "win32", "cp3*-win32"] - [windows-11-arm, "win_arm64", "cp3*-win_arm64"] - - [macos-14, "macos", "cp*-macosx_*"] + - [macos-15, "macos", "cp*-macosx_*"] steps: - name: Checkout pymongo diff --git a/.github/workflows/sbom.yml b/.github/workflows/sbom.yml index 47f2e40d0f..7ce512e656 100644 --- a/.github/workflows/sbom.yml +++ b/.github/workflows/sbom.yml @@ -75,7 +75,7 @@ jobs: if-no-files-found: error - name: Create Pull Request - uses: peter-evans/create-pull-request@5f6978faf089d4d20b00c7766989d076bb2fc7f1 # v8 + uses: peter-evans/create-pull-request@15733dbdfeedb4f7fdb73d13c6f5ac83b710fab8 # v8.1.2 with: token: ${{ secrets.GITHUB_TOKEN }} commit-message: 'chore: Update SBOM after dependency changes' diff --git a/.github/workflows/test-mod-wsgi.yml b/.github/workflows/test-mod-wsgi.yml index 2fa0aaebfe..990a645086 100644 --- a/.github/workflows/test-mod-wsgi.yml +++ b/.github/workflows/test-mod-wsgi.yml @@ -67,7 +67,7 @@ jobs: - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - name: Install just run: | uv tool install rust-just @@ -139,7 +139,7 @@ jobs: - uses: actions/checkout@v7.0.1 with: persist-credentials: false - - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - id: versions uses: $/.github/actions/mod-wsgi-versions with: @@ -161,7 +161,7 @@ jobs: uv pip install -r requirements/mod_wsgi.txt uv run --no-sync python tools/fail_if_no_c.py - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: version: ${{ steps.versions.outputs.mongodb-version }} topology: "replica_set" diff --git a/.github/workflows/test-python.yml b/.github/workflows/test-python.yml index f4f45cf0e1..c103a0cbab 100644 --- a/.github/workflows/test-python.yml +++ b/.github/workflows/test-python.yml @@ -85,7 +85,7 @@ jobs: # The beta Python here relies on the action's prerelease default. python-version: ${{ matrix.python-version }} - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: version: "${{ matrix.mongodb-version }}" - name: Run tests @@ -107,7 +107,7 @@ jobs: with: python-version: "3.11" - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: version: "8.0" - name: Setup tests @@ -135,7 +135,7 @@ jobs: - name: Install dependencies run: just install - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: version: "8.0" - name: Run tests @@ -194,12 +194,12 @@ jobs: - name: Install dependencies run: just install - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 - name: Run tests run: | just integration-tests - id: setup-mongodb-ssl - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: ssl: true - name: Run tests @@ -254,7 +254,7 @@ jobs: # Test sdist on lowest supported Python python-version: "3.11" - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 - name: Run connect test from sdist shell: bash run: | @@ -278,7 +278,7 @@ jobs: with: python-version: "3.11" - id: setup-mongodb - uses: mongodb-labs/drivers-evergreen-tools@3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef # v1.4.1 + uses: mongodb-labs/drivers-evergreen-tools@5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 # v1.6.0 with: version: "8.0" - name: Run tests diff --git a/.github/workflows/uv-lock-update.yml b/.github/workflows/uv-lock-update.yml deleted file mode 100644 index e53641b9c1..0000000000 --- a/.github/workflows/uv-lock-update.yml +++ /dev/null @@ -1,42 +0,0 @@ -name: uv Lock Update - -on: - schedule: - # Tuesdays at 12:00 UTC. - - cron: "0 12 * * 2" - workflow_dispatch: - inputs: - dry_run: - description: "Run without pushing or opening a pull request" - type: boolean - default: false - -permissions: - contents: read - # A live run uses the app token, but a dry run looks up the existing pull - # request with github.token, so that read has to be granted here. - pull-requests: read - -concurrency: - group: uv-lock-update - cancel-in-progress: false - -jobs: - update: - name: Update uv.lock - runs-on: ubuntu-latest - environment: automation - if: github.repository_owner == 'mongodb' || github.event_name == 'workflow_dispatch' - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Install uv - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 - with: - python-version: "3.11" - - uses: mongodb-labs/drivers-github-tools/python/uv-lock-update@99b1cbd729bc83bf7fc74e1b2a97fffad3d65d7b # v3.1.1 - with: - app_id: ${{ vars.APP_ID }} - private_key: ${{ secrets.APP_PRIVATE_KEY }} - dry_run: ${{ inputs.dry_run || 'false' }} diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml index f4e933269f..2517a331ed 100644 --- a/.github/workflows/zizmor.yml +++ b/.github/workflows/zizmor.yml @@ -18,4 +18,4 @@ jobs: with: persist-credentials: false - name: Run zizmor 🌈 - uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 326bf2cf4e..994feb5d30 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -51,13 +51,6 @@ repos: always_run: true pass_filenames: false -- repo: https://github.com/adamchainz/blacken-docs - rev: "1.20.0" - hooks: - - id: blacken-docs - additional_dependencies: - - black==22.3.0 - - repo: https://github.com/pre-commit/pygrep-hooks rev: "v1.10.0" hooks: @@ -136,3 +129,11 @@ repos: language: python require_serial: true additional_dependencies: ["pytest", "pytest-asyncio", "shrub.py>=3.10.0", "pyyaml>=6.0.2"] + - id: evergreen-scripts + name: evergreen-scripts + entry: python -m pytest .evergreen/scripts/test_setup_uv.py -m "" + language: python + require_serial: true + pass_filenames: false + files: ^\.evergreen/scripts/ + additional_dependencies: ["pytest", "pytest-asyncio"] diff --git a/AGENTS.md b/AGENTS.md index 1018b63902..b11b8c09da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,6 +42,9 @@ Async functions must not call blocking I/O. New features need integration tests. Bug fixes need regression tests. +## Dependency updates +Dependabot fully manages `uv.lock`: one grouped weekly pull request plus immediate security pull requests. Never set `[tool.uv] exclude-newer` in `pyproject.toml`; pin `required-version` only when a uv lockfile feature requires it. Details in CONTRIBUTING.md "Dependency updates". + ## Commit and PR Conventions - Prefix commits and PR titles with the JIRA ticket: `PYTHON-1234 Fix retryable write on mongos` - Backport PRs: append the target branch in brackets — `PYTHON-1234 [v4.9] Fix retryable write` diff --git a/CODING-STANDARDS.md b/CODING-STANDARDS.md index 1b42a9df89..ad73f15d36 100644 --- a/CODING-STANDARDS.md +++ b/CODING-STANDARDS.md @@ -1,4 +1,3 @@ - # Intent This document describes the common coding standards for all projects maintained by the Python Drivers team. These standards apply to all written code, comments, and docstrings, both human and machine-authored. Use these guidelines both when writing and reviewing code. @@ -203,4 +202,3 @@ if TYPE_CHECKING: 2. A poor commit message: “2x speedup on inserts (if document \> 1MB).” 4. Extended messages longer than the one line summary are permitted, but are not encouraged as they are squashed during pull-request merge. They may contain periods. 5. Do not force-push to an open PR unless absolutely necessary. - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e683cbc5d1..dd62d8d2f6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -199,12 +199,12 @@ the pages will re-render and the browser will automatically refresh. create a virtual environment and run `pytest` directly. If you want to use a specific version of Python, set `UV_PYTHON` before running `just install`. - `just install` installs the pinned version of `uv` (from `[tool.uv] required-version`) into `$HOME/.local/bin`, - and adds that directory to your shell rc file when missing, so the pinned `uv` takes effect in new shells. If a - project `uv` command (e.g. `just test`) runs with a different `uv` version, `uv` fails fast and tells you how to update. - Scripts inside the vendored `drivers-evergreen-tools` submodule are exempt: the setup scripts write a `uv.toml` - boundary file into that checkout (see `.evergreen/scripts/configure-env.sh`), which stops uv's config discovery - there, since the tools' scripts run uv versions this project does not pin. + `just install` installs the latest `uv` into `$HOME/.local/bin` (no pin) unless the `uv` on PATH + is that copy, and adds that directory to your shell rc file when missing. The fail-fast version check + applies only when a `required-version` pin is set under `[tool.uv]` in `pyproject.toml`. The + vendored `drivers-evergreen-tools` submodule is exempt from this project's uv settings: the setup + scripts write a `uv.toml` boundary into that checkout (see `.evergreen/scripts/configure-env.sh`) + to stop uv's config discovery there. - Ensure you have started the appropriate Mongo Server(s). You can run `just run-server` with optional args to set up the server. All given options will be passed to [`run-mongodb.sh`](https://github.com/mongodb-labs/drivers-evergreen-tools/blob/master/.evergreen/run-mongodb.sh). Run `${DRIVERS_TOOLS:-drivers-evergreen-tools}/.evergreen/run-mongodb.sh start -h` @@ -457,6 +457,10 @@ wheels (CPython 3.12-3.14). - Time-boxed fuzzing (runs daily on Evergreen): `just setup-tests fuzz fuzz` then `just run-tests`. Set `FUZZ_MAX_TIME` (seconds, default 300) to change the per-target budget. +- Nightly fuzzing captures coverage-increasing inputs into `fuzz/corpus/` + via an automated PR (PYTHON-6178); see [fuzz/README.md](fuzz/README.md). + To run that flow on demand, patch the task: + `evergreen patch --variant fuzz-rhel8 --task fuzz`. ## Testing time-dependent operations @@ -481,16 +485,16 @@ Tasks are host-agnostic, so the interpreter lookup happens on the host: for a pl CPython version whose toolchain dir exists, `UV_PYTHON_SEARCH_PATH` points uv at it, and for anything else (a version the toolchain lacks) uv downloads it. - If a specific Python binary is needed (for example on the FIPS host), set `UV_PYTHON=/path/to/python`. - - The default if `UV_PYTHON` is not set is CPython 3.10. This is deterministic across host types, so a task + - The default if `UV_PYTHON` is not set is CPython 3.11. This is deterministic across host types, so a task that does not pin a version always gets the same Python (with the build headers (`Python.h`) needed to build the C extensions). - - The uv binary version is pinned once in `[tool.uv] required-version` in `pyproject.toml`. - `.evergreen/scripts/install-dependencies.sh` installs it with `uv tool install`, uv enforces it locally, and - `astral-sh/setup-uv` reads it on GitHub. Bump it manually when a newer uv is needed. If uv cannot find the - requested Python, it installs it; if that fails, the task fails. The pin is not enforced for scripts inside - the vendored `drivers-evergreen-tools` submodule: those scripts run uv versions this project does not pin, so - the setup scripts write a `uv.toml` boundary into the submodule checkout that stops uv's config discovery - (and with it the required-version check) at the submodule boundary. + - GitHub Actions use the latest uv (`astral-sh/setup-uv`'s default); Evergreen ensures a + project-controlled uv in `UV_TOOL_BIN_DIR` via `ensure-uv.sh` / `setup_uv.py` (the pinned + version when a pin is set, the latest otherwise). A `[tool.uv] required-version` pin is added + only when a needed uv lockfile feature requires it. If uv cannot find the requested Python, it + installs it; if that fails, the task fails. When the MongoDB toolchain provides the requested + version, `setup-uv-python.sh` points `UV_PYTHON` at that interpreter by path, keeping + provisioning independent of the uv version on PATH. - Regenerate the test variants and tasks using `pre-commit run --all-files generate-config`. - PR tasks pin to the Python boundaries: `MIN_PYTHON` with `TEST_MIN_DEPS=1`, `MAX_PYTHON`, and one `FREE_THREADED_PYTHON`, against the newest numbered server (`MAX_VERSION`; the `latest` nightly @@ -500,6 +504,20 @@ CPython version whose toolchain dir exists, `UV_PYTHON_SEARCH_PATH` points uv at diff to confirm the `pr` tags. - Make sure to add instructions for running the test suite to `CONTRIBUTING.md`. +### Sanitizer tests + +The `sanitizer` test suite (PYTHON-6048) builds the C extensions with +`-fsanitize=address,undefined` against the toolchain's ASan/UBSan-instrumented +CPython (`SANITIZER_PYTHON` in `.evergreen/scripts/utils.py`) and runs the +files listed in `SANITIZER_FILES` in `.evergreen/scripts/setup_tests.py`. The +toolchain interpreter initializes the sanitizer runtimes itself. It runs on +PRs via the "Sanitizer RHEL8" variant. To run it on a Linux host with the +toolchain: + + just run-server + just setup-tests sanitizer + just run-tests + ## Handling flaky tests We have a custom `flaky` decorator in [test/asynchronous/utils.py](test/asynchronous/utils.py) that can be used for @@ -573,10 +591,10 @@ git diff HEAD~1 path/to/file >> .evergreen/spec-patch/PYTHON-1234.patch ``` #### Running Locally -Both `resync-all-specs.sh` and `resync-all-specs.py` can be run locally (and won't generate a PR). +Both `resync-all-specs.sh` and `resync_all_specs.py` can be run locally (and won't generate a PR). ```bash ./.evergreen/scripts/resync-all-specs.sh -python3 ./.evergreen/scripts/resync-all-specs.py +python3 ./.evergreen/scripts/resync_all_specs.py ``` ## Making a Release @@ -643,10 +661,18 @@ From the spawn host or Ubuntu image, do the following: ## Dependency updates -Dependabot raises PRs at most once per week for GitHub Actions updates. For Python -dependencies it is limited to security updates, because routine upgrades are handled by -a scheduled workflow that runs weekly, running `uv lock --upgrade` and keeping a single -open pull request on the `uv-lock-update` branch. +Dependabot raises PRs at most once per week for GitHub Actions updates. Dependabot fully +manages `uv.lock`: one grouped weekly pull request with a 7-day cooldown, plus immediate, +ungrouped security updates the cooldown never delays. + +Never set `exclude-newer` under `[tool.uv]` in `pyproject.toml`: Dependabot resolves with +it and produces pull requests that remove or downgrade packages +([dependabot-core#14156](https://github.com/dependabot/dependabot-core/issues/14156)). To +pull a routine update forward past the cooldown, list the package under the cooldown's +`exclude` key in `.github/dependabot.yml`. + +Set `[tool.uv] required-version` only when a needed uv feature requires it, and keep it +satisfiable by the uv version Dependabot ships. If a typing dependency has changed, run `just typing` and handle any new findings. @@ -656,9 +682,7 @@ If a typing dependency has changed, run `just typing` and handle any new finding and in CI. Continuous integration runs `uv lock --check`, which fails when the lock file no longer matches `pyproject.toml`. -If that check fails on your pull request, regenerate the lock file and commit the result. -A 7 day cutoff (`exclude-newer` in `pyproject.toml`) applies automatically, so a package -version yanked shortly after release is less likely to land in the lock file: +If that check fails on your pull request, regenerate the lock file and commit the result: ```bash uv lock diff --git a/bson/__init__.py b/bson/__init__.py index 34b7f7a2f9..4fc30517aa 100644 --- a/bson/__init__.py +++ b/bson/__init__.py @@ -89,9 +89,7 @@ Any, BinaryIO, NoReturn, - Optional, TypeVar, - Union, cast, overload, ) @@ -247,7 +245,7 @@ def get_data_and_view(data: Any) -> tuple[Any, memoryview]: return data, memoryview(data) -def _raw_as_bytes(raw: Union[bytes, bytearray, memoryview]) -> bytes: +def _raw_as_bytes(raw: bytes | bytearray | memoryview) -> bytes: """Convert a raw BSON buffer (bytes, bytearray, or memoryview) to bytes.""" return raw if isinstance(raw, bytes) else bytes(raw) @@ -390,7 +388,7 @@ def _get_array( def _get_binary( data: Any, _view: Any, position: int, obj_end: int, opts: CodecOptions[Any], dummy1: Any -) -> tuple[Union[Binary, uuid.UUID], int]: +) -> tuple[Binary | uuid.UUID, int]: """Decode a BSON binary to bson.binary.Binary or python UUID.""" length, subtype = _UNPACK_LENGTH_SUBTYPE_FROM(data, position) position += 5 @@ -448,7 +446,7 @@ def _get_boolean( def _get_date( data: Any, _view: Any, position: int, dummy0: int, opts: CodecOptions[Any], dummy1: Any -) -> tuple[Union[datetime.datetime, DatetimeMS], int]: +) -> tuple[datetime.datetime | DatetimeMS, int]: """Decode a BSON datetime to python datetime.datetime.""" return _millis_to_datetime(_UNPACK_LONG_FROM(data, position)[0], opts), position + 8 @@ -606,7 +604,7 @@ def _raw_to_dict( result: _T, raw_array: bool = False, ) -> _T: - return cast(_T, _cbson._raw_to_dict(data, position, obj_end, opts, result, raw_array)) + return cast("_T", _cbson._raw_to_dict(data, position, obj_end, opts, result, raw_array)) else: @@ -620,7 +618,8 @@ def _raw_to_dict( ) -> _T: data, view = get_data_and_view(data) return cast( - _T, _elements_to_dict(data, view, position, obj_end, opts, result, raw_array=raw_array) + "_T", + _elements_to_dict(data, view, position, obj_end, opts, result, raw_array=raw_array), ) @@ -677,7 +676,7 @@ def _bson_to_dict(data: Any, opts: CodecOptions[_DocumentType]) -> _DocumentType def gen_list_name() -> Generator[bytes, None, None]: - """Generate "keys" for encoded lists in the sequence + r"""Generate "keys" for encoded lists in the sequence b"0\x00", b"1\x00", b"2\x00", ... The first 1000 keys are returned from a pre-built cache. All @@ -690,7 +689,7 @@ def gen_list_name() -> Generator[bytes, None, None]: yield (str(next(counter)) + "\x00").encode("utf8") -def _make_c_string_check(string: Union[str, bytes]) -> bytes: +def _make_c_string_check(string: str | bytes) -> bytes: """Make a 'C' string, checking for embedded NUL characters.""" if isinstance(string, bytes): if b"\x00" in string: @@ -708,7 +707,7 @@ def _make_c_string_check(string: Union[str, bytes]) -> bytes: return _utf_8_encode(string)[0] + b"\x00" -def _make_c_string(string: Union[str, bytes]) -> bytes: +def _make_c_string(string: str | bytes) -> bytes: """Make a 'C' string.""" if isinstance(string, bytes): try: @@ -952,7 +951,6 @@ def _name_value_to_bson( in_fallback_call: bool = False, ) -> bytes: """Encode a single name, value pair.""" - was_integer_overflow = False # First see if the type is already cached. KeyError will only ever @@ -1093,8 +1091,8 @@ def decode(data: _ReadableBuffer, codec_options: CodecOptions[_DocumentType]) -> def decode( - data: _ReadableBuffer, codec_options: Optional[CodecOptions[_DocumentType]] = None -) -> Union[dict[str, Any], _DocumentType]: + data: _ReadableBuffer, codec_options: CodecOptions[_DocumentType] | None = None +) -> dict[str, Any] | _DocumentType: """Decode BSON to a document. By default, returns a BSON document represented as a Python @@ -1123,7 +1121,7 @@ def decode( if not isinstance(opts, CodecOptions): raise _CODEC_OPTIONS_TYPE_ERROR - return cast("Union[dict[str, Any], _DocumentType]", _bson_to_dict(data, opts)) + return cast("dict[str, Any] | _DocumentType", _bson_to_dict(data, opts)) def _decode_all(data: _ReadableBuffer, opts: CodecOptions[_DocumentType]) -> list[_DocumentType]: @@ -1176,8 +1174,8 @@ def decode_all( def decode_all( - data: _ReadableBuffer, codec_options: Optional[CodecOptions[_DocumentType]] = None -) -> Union[list[dict[str, Any]], list[_DocumentType]]: + data: _ReadableBuffer, codec_options: CodecOptions[_DocumentType] | None = None +) -> list[dict[str, Any]] | list[_DocumentType]: """Decode BSON data to multiple documents. `data` must be a bytes-like object implementing the buffer protocol that @@ -1231,7 +1229,7 @@ def _decode_selective( return doc -def _array_of_documents_to_buffer(data: Union[memoryview, bytes]) -> bytes: +def _array_of_documents_to_buffer(data: memoryview | bytes) -> bytes: # Extract the raw bytes of each document. position = 0 view = memoryview(data) @@ -1328,8 +1326,8 @@ def decode_iter( def decode_iter( - data: bytes, codec_options: Optional[CodecOptions[_DocumentType]] = None -) -> Union[Iterator[dict[str, Any]], Iterator[_DocumentType]]: + data: bytes, codec_options: CodecOptions[_DocumentType] | None = None +) -> Iterator[dict[str, Any]] | Iterator[_DocumentType]: """Decode BSON data to multiple documents as a generator. Works similarly to the decode_all function, but yields one document at a @@ -1364,20 +1362,20 @@ def decode_iter( @overload def decode_file_iter( - file_obj: Union[BinaryIO, IO[bytes]], codec_options: None = None + file_obj: BinaryIO | IO[bytes], codec_options: None = None ) -> Iterator[dict[str, Any]]: ... @overload def decode_file_iter( - file_obj: Union[BinaryIO, IO[bytes]], codec_options: CodecOptions[_DocumentType] + file_obj: BinaryIO | IO[bytes], codec_options: CodecOptions[_DocumentType] ) -> Iterator[_DocumentType]: ... def decode_file_iter( - file_obj: Union[BinaryIO, IO[bytes]], - codec_options: Optional[CodecOptions[_DocumentType]] = None, -) -> Union[Iterator[dict[str, Any]], Iterator[_DocumentType]]: + file_obj: BinaryIO | IO[bytes], + codec_options: CodecOptions[_DocumentType] | None = None, +) -> Iterator[dict[str, Any]] | Iterator[_DocumentType]: """Decode bson data from a file to multiple documents as a generator. Works similarly to the decode_all function, but reads from the file object diff --git a/bson/_helpers.py b/bson/_helpers.py index 6f05878b5d..596965a138 100644 --- a/bson/_helpers.py +++ b/bson/_helpers.py @@ -18,8 +18,10 @@ from __future__ import annotations -from collections.abc import Mapping -from typing import Any +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Mapping def _setstate_slots(self: Any, state: Any) -> None: diff --git a/bson/binary.py b/bson/binary.py index 85f59db527..4409fa4b7a 100644 --- a/bson/binary.py +++ b/bson/binary.py @@ -15,9 +15,8 @@ import struct import warnings -from collections.abc import Sequence from enum import Enum -from typing import TYPE_CHECKING, Any, Optional, Union, overload +from typing import TYPE_CHECKING, Any, Self, overload from uuid import UUID """Tools for representing BSON binary data. @@ -64,6 +63,7 @@ if TYPE_CHECKING: from array import array as _array + from collections.abc import Sequence from mmap import mmap as _mmap import numpy as np @@ -240,7 +240,7 @@ class BinaryVector: def __init__( self, - data: Union[Sequence[float | int], npt.NDArray[np.number]], + data: Sequence[float | int] | npt.NDArray[np.number], dtype: BinaryVectorDtype, padding: int = 0, ): @@ -260,7 +260,7 @@ def __init__( def __repr__(self) -> str: return f"BinaryVector(dtype={self.dtype}, padding={self.padding}, data={self.data})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if not isinstance(other, BinaryVector): return False return ( @@ -310,10 +310,10 @@ class Binary(bytes): __subtype: int def __new__( - cls: type[Binary], - data: Union[memoryview, bytes, bytearray, _mmap, _array[Any]], + cls, + data: memoryview | bytes | bytearray | _mmap | _array[Any], subtype: int = BINARY_SUBTYPE, - ) -> Binary: + ) -> Self: if not isinstance(subtype, int): raise TypeError(f"subtype must be an instance of int, not {type(subtype)}") if subtype >= 256 or subtype < 0: @@ -434,7 +434,7 @@ def from_vector(cls: type[Binary], vector: BinaryVector) -> Binary: ... @overload def from_vector( cls: type[Binary], - vector: Union[list[int], list[float]], + vector: list[int] | list[float], dtype: BinaryVectorDtype, padding: int = 0, ) -> Binary: ... @@ -451,9 +451,9 @@ def from_vector( @classmethod def from_vector( cls: type[Binary], - vector: Union[BinaryVector, list[int], list[float], npt.NDArray[np.number]], - dtype: Optional[BinaryVectorDtype] = None, - padding: Optional[int] = None, + vector: BinaryVector | list[int] | list[float] | npt.NDArray[np.number], + dtype: BinaryVectorDtype | None = None, + padding: int | None = None, ) -> Binary: """Create a BSON :class:`~bson.binary.Binary` of Vector subtype. @@ -553,7 +553,6 @@ def as_vector(self, return_numpy: bool = False) -> BinaryVector: .. versionadded:: 4.10 """ - if self.subtype != VECTOR_SUBTYPE: raise ValueError(f"Cannot decode subtype {self.subtype} as a vector") @@ -648,7 +647,7 @@ def __getnewargs__(self) -> tuple[bytes, int]: # type: ignore[override] data = data.encode("latin-1") return data, self.__subtype - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Binary): return (self.__subtype, bytes(self)) == (other.subtype, bytes(other)) # We don't return NotImplemented here because if we did then @@ -659,7 +658,7 @@ def __eq__(self, other: Any) -> bool: def __hash__(self) -> int: return super().__hash__() ^ hash(self.__subtype) - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: diff --git a/bson/buffer.c b/bson/buffer.c index 68a8fe3590..c7df462980 100644 --- a/bson/buffer.c +++ b/bson/buffer.c @@ -85,11 +85,16 @@ static int buffer_grow(buffer_t buffer, int min_length) { } while (size < min_length) { old_size = size; - size *= 2; - if (size <= old_size) { - /* Size did not increase. Could be an overflow - * or size < 1. Just go with min_length. */ - size = min_length; + if (size > INT_MAX / 2) { + /* Doubling `size` would overflow `int`; grow to exactly + * min_length instead. */ + size = min_length; + } else { + size *= 2; + if (size <= old_size) { + /* Size did not increase. Could be size < 1. */ + size = min_length; + } } } buffer->buffer = (char*)realloc(buffer->buffer, sizeof(char) * size); diff --git a/bson/code.py b/bson/code.py index 983c566a3d..60193e12f5 100644 --- a/bson/code.py +++ b/bson/code.py @@ -18,7 +18,7 @@ from collections.abc import Mapping from collections.abc import Mapping as _Mapping -from typing import Any, Optional, Union +from typing import Any, Self class Code(str): @@ -49,14 +49,14 @@ class Code(str): """ _type_marker = 13 - __scope: Union[Mapping[str, Any], None] + __scope: Mapping[str, Any] | None def __new__( - cls: type[Code], - code: Union[str, Code], - scope: Optional[Mapping[str, Any]] = None, + cls, + code: str | Code, + scope: Mapping[str, Any] | None = None, **kwargs: Any, - ) -> Code: + ) -> Self: if not isinstance(code, str): raise TypeError(f"code must be an instance of str, not {type(code)}") @@ -84,19 +84,19 @@ def __new__( return self @property - def scope(self) -> Optional[Mapping[str, Any]]: + def scope(self) -> Mapping[str, Any] | None: """Scope dictionary for this instance or ``None``.""" return self.__scope def __repr__(self) -> str: return f"Code({str.__repr__(self)}, {self.__scope!r})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Code): return (self.__scope, str(self)) == (other.__scope, str(other)) return False __hash__: Any = None - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other diff --git a/bson/codec_options.py b/bson/codec_options.py index df18b9c715..a7064804a5 100644 --- a/bson/codec_options.py +++ b/bson/codec_options.py @@ -26,8 +26,7 @@ Any, Generic, NamedTuple, - Optional, - Union, + Self, cast, ) @@ -36,7 +35,6 @@ UUID_REPRESENTATION_NAMES, UuidRepresentation, ) -from bson.typings import _DocumentType _RAW_BSON_DOCUMENT_MARKER = 101 @@ -103,7 +101,7 @@ class TypeCodec(TypeEncoder, TypeDecoder): """ -_Codec = Union[TypeEncoder, TypeDecoder, TypeCodec] +_Codec = TypeEncoder | TypeDecoder | TypeCodec _Fallback = Callable[[Any], Any] @@ -135,8 +133,8 @@ class TypeRegistry: def __init__( self, - type_codecs: Optional[Iterable[_Codec]] = None, - fallback_encoder: Optional[_Fallback] = None, + type_codecs: Iterable[_Codec] | None = None, + fallback_encoder: _Fallback | None = None, ) -> None: self.__type_codecs = list(type_codecs or []) self._fallback_encoder = fallback_encoder @@ -167,7 +165,7 @@ def codecs(self) -> list[TypeEncoder | TypeDecoder | TypeCodec]: return self.__type_codecs @property - def fallback_encoder(self) -> Optional[_Fallback]: + def fallback_encoder(self) -> _Fallback | None: """The fallback encoder in this registry.""" return self._fallback_encoder @@ -175,7 +173,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None: from bson import _BUILT_IN_TYPES for pytype in _BUILT_IN_TYPES: - if issubclass(cast(TypeCodec, codec).python_type, pytype): + if issubclass(cast("TypeCodec", codec).python_type, pytype): err_msg = ( "TypeEncoders cannot change how built-in types are " f"encoded (encoder {codec} transforms type {pytype})" @@ -185,7 +183,7 @@ def _validate_type_encoder(self, codec: _Codec) -> None: def __repr__(self) -> str: return f"{self.__class__.__name__}(type_codecs={self.__type_codecs!r}, fallback_encoder={self._fallback_encoder!r})" - def __eq__(self, other: Any) -> Any: + def __eq__(self, other: object) -> Any: if not isinstance(other, type(self)): return NotImplemented return ( @@ -237,31 +235,32 @@ class _BaseCodecOptions(NamedTuple): tz_aware: bool uuid_representation: int unicode_decode_error_handler: str - tzinfo: Optional[datetime.tzinfo] + tzinfo: datetime.tzinfo | None type_registry: TypeRegistry - datetime_conversion: Optional[DatetimeConversion] + datetime_conversion: DatetimeConversion | None if TYPE_CHECKING: + from bson.typings import _DocumentType class CodecOptions(tuple[_DocumentType], Generic[_DocumentType]): document_class: type[_DocumentType] tz_aware: bool uuid_representation: int - unicode_decode_error_handler: Optional[str] - tzinfo: Optional[datetime.tzinfo] + unicode_decode_error_handler: str | None + tzinfo: datetime.tzinfo | None type_registry: TypeRegistry - datetime_conversion: Optional[int] + datetime_conversion: int | None def __new__( cls: type[CodecOptions[_DocumentType]], - document_class: Optional[type[_DocumentType]] = ..., + document_class: type[_DocumentType] | None = ..., tz_aware: bool = ..., - uuid_representation: Optional[int] = ..., - unicode_decode_error_handler: Optional[str] = ..., - tzinfo: Optional[datetime.tzinfo] = ..., - type_registry: Optional[TypeRegistry] = ..., - datetime_conversion: Optional[int] = ..., + uuid_representation: int | None = ..., + unicode_decode_error_handler: str | None = ..., + tzinfo: datetime.tzinfo | None = ..., + type_registry: TypeRegistry | None = ..., + datetime_conversion: int | None = ..., ) -> CodecOptions[_DocumentType]: ... # CodecOptions API @@ -286,7 +285,7 @@ class CodecOptions(_BaseCodecOptions): """Encapsulates options used encoding and / or decoding BSON.""" def __init__(self, *args, **kwargs): - """Encapsulates options used encoding and / or decoding BSON. + r"""Encapsulates options used encoding and / or decoding BSON. The `document_class` option is used to define a custom type for use decoding BSON documents. Access to the underlying raw BSON bytes for @@ -299,7 +298,7 @@ def __init__(self, *args, **kwargs): >>> coll = db.get_collection('test', codec_options=codec_options) >>> doc = coll.find_one() >>> doc.raw - '\\x16\\x00\\x00\\x00\\x07_id\\x00[0\\x165\\x91\\x10\\xea\\x14\\xe8\\xc5\\x8b\\x93\\x00' + '\x16\x00\x00\x00\x07_id\x00[0\x165\x91\x10\xea\x14\xe8\xc5\x8b\x93\x00' The document class can be any type that inherits from :class:`~collections.abc.MutableMapping`:: @@ -370,15 +369,15 @@ def __init__(self, *args, **kwargs): super().__init__() def __new__( - cls: type[CodecOptions], - document_class: Optional[type[Mapping[str, Any]]] = None, + cls, + document_class: type[Mapping[str, Any]] | None = None, tz_aware: bool = False, - uuid_representation: Optional[int] = UuidRepresentation.UNSPECIFIED, + uuid_representation: int | None = UuidRepresentation.UNSPECIFIED, unicode_decode_error_handler: str = "strict", - tzinfo: Optional[datetime.tzinfo] = None, - type_registry: Optional[TypeRegistry] = None, - datetime_conversion: Optional[DatetimeConversion] = DatetimeConversion.DATETIME, - ) -> CodecOptions: + tzinfo: datetime.tzinfo | None = None, + type_registry: TypeRegistry | None = None, + datetime_conversion: DatetimeConversion | None = DatetimeConversion.DATETIME, + ) -> Self: doc_class = document_class or dict # Generic aliases like SON[str, Any] or dict[str, Any] aren't classes, so # resolve to their origin before the subclass check. issubclass() raises @@ -402,7 +401,7 @@ def __new__( "uuid_representation must be a value from bson.binary.UuidRepresentation" ) if not isinstance(unicode_decode_error_handler, str): - raise ValueError( + raise TypeError( f"unicode_decode_error_handler must be a string, not {type(unicode_decode_error_handler)}" ) if tzinfo is not None: diff --git a/bson/datetime_ms.py b/bson/datetime_ms.py index f5a38e63f6..d659323717 100644 --- a/bson/datetime_ms.py +++ b/bson/datetime_ms.py @@ -21,7 +21,7 @@ import calendar import datetime -from typing import Any, Union, cast +from typing import Any, cast from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, DatetimeConversion from bson.errors import InvalidBSON @@ -41,7 +41,7 @@ class DatetimeMS: __slots__ = ("_value",) - def __init__(self, value: Union[int, datetime.datetime]): + def __init__(self, value: int | datetime.datetime): """Represents a BSON UTC datetime. BSON UTC datetimes are defined as an int64 of milliseconds since the @@ -74,26 +74,26 @@ def __hash__(self) -> int: def __repr__(self) -> str: return type(self).__name__ + "(" + str(self._value) + ")" - def __lt__(self, other: Union[DatetimeMS, int]) -> bool: + def __lt__(self, other: DatetimeMS | int) -> bool: return self._value < other - def __le__(self, other: Union[DatetimeMS, int]) -> bool: + def __le__(self, other: DatetimeMS | int) -> bool: return self._value <= other - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, DatetimeMS): return self._value == other._value return False - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: if isinstance(other, DatetimeMS): return self._value != other._value return True - def __gt__(self, other: Union[DatetimeMS, int]) -> bool: + def __gt__(self, other: DatetimeMS | int) -> bool: return self._value > other - def __ge__(self, other: Union[DatetimeMS, int]) -> bool: + def __ge__(self, other: DatetimeMS | int) -> bool: return self._value >= other _type_marker = 9 @@ -108,7 +108,7 @@ def as_datetime( and ``tz_info``. Defaults to :const:`~bson.codec_options.DEFAULT_CODEC_OPTIONS`. """ - return cast(datetime.datetime, _millis_to_datetime(self._value, codec_options)) + return cast("datetime.datetime", _millis_to_datetime(self._value, codec_options)) def __int__(self) -> int: return self._value @@ -146,9 +146,7 @@ def _max_datetime_ms(tz: datetime.tzinfo = utc) -> int: return min(_MAX_UTC_MS, _MAX_UTC_MS - offset_millis) -def _millis_to_datetime( - millis: int, opts: CodecOptions[Any] -) -> Union[datetime.datetime, DatetimeMS]: +def _millis_to_datetime(millis: int, opts: CodecOptions[Any]) -> datetime.datetime | DatetimeMS: """Convert milliseconds since epoch UTC to datetime.""" if ( opts.datetime_conversion == DatetimeConversion.DATETIME diff --git a/bson/dbref.py b/bson/dbref.py index a6bcb467ab..90f0d7d733 100644 --- a/bson/dbref.py +++ b/bson/dbref.py @@ -16,13 +16,15 @@ from __future__ import annotations -from collections.abc import Mapping from copy import deepcopy -from typing import Any, Optional +from typing import TYPE_CHECKING, Any from bson._helpers import _getstate_slots, _setstate_slots from bson.son import SON +if TYPE_CHECKING: + from collections.abc import Mapping + class DBRef: """A reference to a document stored in MongoDB.""" @@ -37,8 +39,8 @@ def __init__( self, collection: str, id: Any, - database: Optional[str] = None, - _extra: Optional[Mapping[str, Any]] = None, + database: str | None = None, + _extra: Mapping[str, Any] | None = None, **kwargs: Any, ) -> None: """Initialize a new :class:`DBRef`. @@ -79,7 +81,7 @@ def id(self) -> Any: return self.__id @property - def database(self) -> Optional[str]: + def database(self) -> str | None: """Get the name of this DBRef's database. Returns None if this DBRef doesn't specify a database. @@ -109,14 +111,14 @@ def __repr__(self) -> str: return f"DBRef({self.collection!r}, {self.id!r}{extra})" return f"DBRef({self.collection!r}, {self.id!r}, {self.database!r}{extra})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, DBRef): us = (self.__database, self.__collection, self.__id, self.__kwargs) them = (other.__database, other.__collection, other.__id, other.__kwargs) return us == them return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: diff --git a/bson/decimal128.py b/bson/decimal128.py index b7304fc3f0..1e62d1767b 100644 --- a/bson/decimal128.py +++ b/bson/decimal128.py @@ -23,7 +23,7 @@ import struct from collections.abc import Sequence from decimal import Decimal -from typing import Any, Union +from typing import Any from bson.codec_options import TypeDecoder, TypeEncoder @@ -61,7 +61,7 @@ } _DEC128_CTX = decimal.Context(**_CTX_OPTIONS.copy()) # type: ignore -_VALUE_OPTIONS = Union[decimal.Decimal, float, str, tuple[int, Sequence[int], int]] +_VALUE_OPTIONS = decimal.Decimal | float | str | tuple[int, Sequence[int], int] class DecimalEncoder(TypeEncoder): @@ -350,12 +350,12 @@ def __setstate__(self, value: tuple[int, int]) -> None: def __getstate__(self) -> tuple[int, int]: return self.__high, self.__low - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Decimal128): return self.bid == other.bid return NotImplemented __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other diff --git a/bson/errors.py b/bson/errors.py index a9e082ec11..0eaec5ed22 100644 --- a/bson/errors.py +++ b/bson/errors.py @@ -16,7 +16,7 @@ from __future__ import annotations -from typing import Any, Optional +from typing import Any class BSONError(Exception): @@ -34,7 +34,7 @@ class InvalidStringData(BSONError): class InvalidDocument(BSONError): """Raised when trying to create a BSON object from an invalid document.""" - def __init__(self, message: str, document: Optional[Any] = None) -> None: + def __init__(self, message: str, document: Any | None = None) -> None: super().__init__(message) self._document = document @@ -42,7 +42,8 @@ def __init__(self, message: str, document: Optional[Any] = None) -> None: def document(self) -> Any: """The invalid document that caused the error. - ..versionadded:: 4.16""" + .. versionadded:: 4.16 + """ return self._document diff --git a/bson/json_util.py b/bson/json_util.py index 01f9f0497d..6f32683b17 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Tools for using Python's :mod:`json` module with BSON documents. +r"""Tools for using Python's :mod:`json` module with BSON documents. This module provides two helper methods `dumps` and `loads` that wrap the native :mod:`json` methods and provide explicit BSON conversion to and from @@ -115,8 +115,7 @@ from typing import ( TYPE_CHECKING, Any, - Optional, - Union, + Self, cast, ) @@ -142,12 +141,12 @@ from bson.tz_util import utc _RE_OPT_TABLE = { - "i": re.I, - "l": re.L, - "m": re.M, - "s": re.S, - "u": re.U, - "x": re.X, + "i": re.IGNORECASE, + "l": re.LOCALE, + "m": re.MULTILINE, + "s": re.DOTALL, + "u": re.UNICODE, + "x": re.VERBOSE, } @@ -302,14 +301,14 @@ def __init__(self, *args: Any, **kwargs: Any): super().__init__() def __new__( - cls: type[JSONOptions], - strict_number_long: Optional[bool] = None, - datetime_representation: Optional[int] = None, - strict_uuid: Optional[bool] = None, + cls, + strict_number_long: bool | None = None, + datetime_representation: int | None = None, + strict_uuid: bool | None = None, json_mode: int = JSONMode.RELAXED, *args: Any, **kwargs: Any, - ) -> JSONOptions: + ) -> Self: kwargs["tz_aware"] = kwargs.get("tz_aware", False) if kwargs["tz_aware"]: kwargs["tzinfo"] = kwargs.get("tzinfo", utc) @@ -323,7 +322,7 @@ def __new__( "JSONOptions.datetime_representation must be one of LEGACY, " "NUMBERLONG, or ISO8601 from DatetimeRepresentation." ) - self = cast(JSONOptions, super().__new__(cls, *args, **kwargs)) + self = cast("Self", super().__new__(cls, *args, **kwargs)) if json_mode not in (JSONMode.LEGACY, JSONMode.RELAXED, JSONMode.CANONICAL): raise ValueError( "JSONOptions.json_mode must be one of LEGACY, RELAXED, or CANONICAL from JSONMode." @@ -452,7 +451,7 @@ def dumps(obj: Any, *args: Any, **kwargs: Any) -> str: return json.dumps(_json_convert(obj, json_options), *args, **kwargs) -def loads(s: Union[str, bytes, bytearray], *args: Any, **kwargs: Any) -> Any: +def loads(s: str | bytes | bytearray, *args: Any, **kwargs: Any) -> Any: """Helper function that wraps :func:`json.loads`. Automatically passes the object_hook for BSON type conversion. @@ -529,7 +528,7 @@ def _parse_legacy_regex(doc: Any, dummy0: Any) -> Any: return Regex(pattern, flags) -def _parse_legacy_uuid(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]: +def _parse_legacy_uuid(doc: Any, json_options: JSONOptions) -> Binary | uuid.UUID: """Decode a JSON legacy $uuid to Python UUID.""" if len(doc) != 1: raise TypeError(f"Bad $uuid, extra field(s): {doc}") @@ -541,7 +540,7 @@ def _parse_legacy_uuid(doc: Any, json_options: JSONOptions) -> Union[Binary, uui return uuid.UUID(doc["$uuid"]) -def _binary_or_uuid(data: Any, subtype: int, json_options: JSONOptions) -> Union[Binary, uuid.UUID]: +def _binary_or_uuid(data: Any, subtype: int, json_options: JSONOptions) -> Binary | uuid.UUID: # special handling for UUID if subtype in ALL_UUID_SUBTYPES: uuid_representation = json_options.uuid_representation @@ -558,11 +557,11 @@ def _binary_or_uuid(data: Any, subtype: int, json_options: JSONOptions) -> Union return binary_value.as_uuid(uuid_representation) if subtype == 0: - return cast(uuid.UUID, data) + return cast("uuid.UUID", data) return Binary(data, subtype) -def _parse_legacy_binary(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]: +def _parse_legacy_binary(doc: Any, json_options: JSONOptions) -> Binary | uuid.UUID: if isinstance(doc["$type"], int): doc["$type"] = "{:02x}".format(doc["$type"]) subtype = int(doc["$type"], 16) @@ -572,7 +571,7 @@ def _parse_legacy_binary(doc: Any, json_options: JSONOptions) -> Union[Binary, u return _binary_or_uuid(data, subtype, json_options) -def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]: +def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Binary | uuid.UUID: binary = doc["$binary"] b64 = binary["base64"] subtype = binary["subType"] @@ -589,7 +588,7 @@ def _parse_canonical_binary(doc: Any, json_options: JSONOptions) -> Union[Binary def _parse_canonical_datetime( doc: Any, json_options: JSONOptions -) -> Union[datetime.datetime, DatetimeMS]: +) -> datetime.datetime | DatetimeMS: """Decode a JSON datetime to python datetime.datetime.""" dtm = doc["$date"] if len(doc) != 1: @@ -782,7 +781,7 @@ def _parse_canonical_maxkey(doc: Any, dummy0: Any) -> MaxKey: return MaxKey() -def _parse_binary(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUID]: +def _parse_binary(doc: Any, json_options: JSONOptions) -> Binary | uuid.UUID: if "$type" in doc: return _parse_legacy_binary(doc, json_options) else: diff --git a/bson/max_key.py b/bson/max_key.py index 0c4e7cffc2..69d4a7b12e 100644 --- a/bson/max_key.py +++ b/bson/max_key.py @@ -32,13 +32,13 @@ def __getstate__(self) -> Any: def __setstate__(self, state: Any) -> None: pass - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: return isinstance(other, MaxKey) def __hash__(self) -> int: return hash(self._type_marker) - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __le__(self, other: Any) -> bool: diff --git a/bson/min_key.py b/bson/min_key.py index 5324e74fab..8a026129f7 100644 --- a/bson/min_key.py +++ b/bson/min_key.py @@ -32,13 +32,13 @@ def __getstate__(self) -> Any: def __setstate__(self, state: Any) -> None: pass - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: return isinstance(other, MinKey) def __hash__(self) -> int: return hash(self._type_marker) - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __le__(self, dummy: Any) -> bool: diff --git a/bson/objectid.py b/bson/objectid.py index c5591aaac4..d4c9dce545 100644 --- a/bson/objectid.py +++ b/bson/objectid.py @@ -22,7 +22,7 @@ import threading import time from random import SystemRandom -from typing import Any, NoReturn, Optional, Union +from typing import Any, NoReturn from bson.datetime_ms import _datetime_to_millis from bson.errors import InvalidId @@ -59,7 +59,7 @@ class ObjectId: _type_marker = 7 - def __init__(self, oid: Optional[Union[str, ObjectId, bytes]] = None) -> None: + def __init__(self, oid: str | ObjectId | bytes | None = None) -> None: """Initialize a new ObjectId. An ObjectId is a 12-byte unique identifier consisting of: @@ -227,12 +227,12 @@ def __str__(self) -> str: def __repr__(self) -> str: return f"ObjectId('{self!s}')" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, ObjectId): return self.__id == other.binary return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: if isinstance(other, ObjectId): return self.__id != other.binary return NotImplemented diff --git a/bson/raw_bson.py b/bson/raw_bson.py index 411916fc7a..2bc91dfa13 100644 --- a/bson/raw_bson.py +++ b/bson/raw_bson.py @@ -55,7 +55,7 @@ import copyreg from collections.abc import ItemsView, Iterator, Mapping -from typing import Any, Optional +from typing import Any from bson import _get_object_size, _raw_as_bytes, _raw_to_dict from bson.codec_options import _RAW_BSON_DOCUMENT_MARKER, CodecOptions @@ -92,7 +92,7 @@ class RawBSONDocument(Mapping[str, Any]): def __init__( self, bson_bytes: bytes | memoryview, - codec_options: Optional[CodecOptions[RawBSONDocument]] = None, + codec_options: CodecOptions[RawBSONDocument] | None = None, ) -> None: """Create a new :class:`RawBSONDocument` @@ -127,7 +127,7 @@ class from the standard library so it can be used like a read-only `document_class` must be :class:`RawBSONDocument`. """ self.__raw = bson_bytes - self.__inflated_doc: Optional[Mapping[str, Any]] = None + self.__inflated_doc: Mapping[str, Any] | None = None # Can't default codec_options to DEFAULT_RAW_BSON_OPTIONS in signature, # it refers to this class RawBSONDocument. if codec_options is None: @@ -182,14 +182,14 @@ def __iter__(self) -> Iterator[str]: def __len__(self) -> int: return len(self.__inflated) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, RawBSONDocument): return self.__raw == other.raw return NotImplemented __hash__ = None # type: ignore[assignment] - def __getstate__(self) -> tuple[Optional[dict[str, Any]], dict[str, Any]]: + def __getstate__(self) -> tuple[dict[str, Any] | None, dict[str, Any]]: slots_state: dict[str, Any] = { name: getattr(self, name) for name in copyreg._slotnames(type(self)) # type: ignore[attr-defined] diff --git a/bson/regex.py b/bson/regex.py index 39d1814fa0..c20a1c5f38 100644 --- a/bson/regex.py +++ b/bson/regex.py @@ -18,7 +18,7 @@ import re from re import Pattern -from typing import Any, Generic, TypeVar, Union +from typing import Any, Generic, TypeVar from bson._helpers import _getstate_slots, _setstate_slots from bson.son import RE_TYPE @@ -84,7 +84,7 @@ def from_native(cls: type[Regex[Any]], regex: Pattern[_T]) -> Regex[_T]: return Regex(regex.pattern, regex.flags) - def __init__(self, pattern: _T, flags: Union[str, int] = 0) -> None: + def __init__(self, pattern: _T, flags: str | int = 0) -> None: """BSON regular expression data. This class is useful to store and retrieve regular expressions that are @@ -105,7 +105,7 @@ def __init__(self, pattern: _T, flags: Union[str, int] = 0) -> None: else: raise TypeError(f"flags must be a string or int, not {type(flags)}") - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Regex): return self.pattern == other.pattern and self.flags == other.flags else: @@ -113,7 +113,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: diff --git a/bson/son.py b/bson/son.py index 84b8028069..2dce98bf4b 100644 --- a/bson/son.py +++ b/bson/son.py @@ -29,9 +29,7 @@ from re import Pattern from typing import ( Any, - Optional, TypeVar, - Union, cast, ) @@ -56,7 +54,7 @@ class SON(dict[_Key, _Value]): def __init__( self, - data: Optional[Union[Mapping[_Key, _Value], Iterable[tuple[_Key, _Value]]]] = None, + data: Mapping[_Key, _Value] | Iterable[tuple[_Key, _Value]] | None = None, **kwargs: Any, ) -> None: self.__keys = [] @@ -70,9 +68,7 @@ def __new__(cls: type[SON[_Key, _Value]], *args: Any, **kwargs: Any) -> SON[_Key return instance def __repr__(self) -> str: - result = [] - for key in self.__keys: - result.append(f"({key!r}, {self[key]!r})") + result = [f"({key!r}, {self[key]!r})" for key in self.__keys] return "SON([{}])".format(", ".join(result)) def __setitem__(self, key: _Key, value: _Value) -> None: @@ -118,7 +114,7 @@ def itervalues(self) -> Iterator[_Value]: DeprecationWarning, stacklevel=2, ) - for _, v in self.items(): + for _, v in self.items(): # noqa: PERF102 yield v def values(self) -> list[_Value]: # type: ignore[override] @@ -135,7 +131,7 @@ def setdefault(self, key: _Key, default: _Value) -> _Value: self[key] = default return default - def pop(self, key: _Key, *args: Union[_Value, _T]) -> Union[_Value, _T]: + def pop(self, key: _Key, *args: _Value | _T) -> _Value | _T: if len(args) > 1: raise TypeError("pop expected at most 2 arguments, got " + repr(1 + len(args))) try: @@ -155,7 +151,7 @@ def popitem(self) -> tuple[_Key, _Value]: del self[k] return (k, v) - def update(self, other: Optional[Any] = None, **kwargs: _Value) -> None: + def update(self, other: Any | None = None, **kwargs: _Value) -> None: # Make progressively weaker assumptions about "other" if other is None: pass @@ -172,24 +168,24 @@ def update(self, other: Optional[Any] = None, **kwargs: _Value) -> None: self.update(kwargs) def get( # type: ignore[override] - self, key: _Key, default: Optional[Union[_Value, _T]] = None - ) -> Union[_Value, _T, None]: + self, key: _Key, default: _Value | _T | None = None + ) -> _Value | _T | None: try: return self[key] except KeyError: return default - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: """Comparison to another SON is order-sensitive while comparison to a regular dictionary is order-insensitive. """ if isinstance(other, SON): return len(self) == len(other) and list(self.items()) == list(other.items()) - return cast(bool, self.to_dict() == other) + return self.to_dict() == other __hash__ = None - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __len__(self) -> int: diff --git a/bson/timestamp.py b/bson/timestamp.py index 02a3fff627..c346623604 100644 --- a/bson/timestamp.py +++ b/bson/timestamp.py @@ -18,7 +18,7 @@ import calendar import datetime -from typing import Any, Union +from typing import Any from bson._helpers import _getstate_slots, _setstate_slots from bson.tz_util import utc @@ -36,7 +36,7 @@ class Timestamp: _type_marker = 17 - def __init__(self, time: Union[datetime.datetime, int], inc: int) -> None: + def __init__(self, time: datetime.datetime | int, inc: int) -> None: """Create a new :class:`Timestamp`. This class is only for use with the MongoDB opLog. If you need @@ -80,7 +80,7 @@ def inc(self) -> int: """Get the inc portion of this :class:`Timestamp`.""" return self.__inc - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Timestamp): return self.__time == other.time and self.__inc == other.inc else: @@ -89,7 +89,7 @@ def __eq__(self, other: Any) -> bool: def __hash__(self) -> int: return hash(self.time) ^ hash(self.inc) - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __lt__(self, other: Any) -> bool: diff --git a/bson/typings.py b/bson/typings.py index 3823182531..593cf2c73d 100644 --- a/bson/typings.py +++ b/bson/typings.py @@ -28,6 +28,6 @@ # Common Shared Types. _DocumentOut = Union[MutableMapping[str, Any], "RawBSONDocument"] -_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any]) -_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any]) +_DocumentType = TypeVar("_DocumentType", bound=Mapping[str, Any]) # noqa: PYI018 +_DocumentTypeArg = TypeVar("_DocumentTypeArg", bound=Mapping[str, Any]) # noqa: PYI018 _ReadableBuffer = Union[bytes, memoryview, bytearray, "mmap", "array"] # type: ignore[type-arg] diff --git a/bson/tz_util.py b/bson/tz_util.py index 18a543633e..249f1aa38a 100644 --- a/bson/tz_util.py +++ b/bson/tz_util.py @@ -17,7 +17,6 @@ from __future__ import annotations from datetime import datetime, timedelta, tzinfo -from typing import Optional, Union ZERO: timedelta = timedelta(0) @@ -30,7 +29,7 @@ class FixedOffset(tzinfo): Defining __getinitargs__ enables pickling / copying. """ - def __init__(self, offset: Union[float, timedelta], name: str) -> None: + def __init__(self, offset: float | timedelta, name: str) -> None: if isinstance(offset, timedelta): self.__offset = offset else: @@ -43,13 +42,13 @@ def __getinitargs__(self) -> tuple[timedelta, str]: def __repr__(self) -> str: return f"{self.__class__.__name__}({self.__offset!r}, {self.__name!r})" - def utcoffset(self, dt: Optional[datetime]) -> timedelta: + def utcoffset(self, dt: datetime | None) -> timedelta: return self.__offset - def tzname(self, dt: Optional[datetime]) -> str: + def tzname(self, dt: datetime | None) -> str: return self.__name - def dst(self, dt: Optional[datetime]) -> timedelta: + def dst(self, dt: datetime | None) -> timedelta: return ZERO diff --git a/doc/changelog.rst b/doc/changelog.rst index dc0e697fdf..d4e6193715 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -1,11 +1,36 @@ Changelog ========= -Changes in Version 4.20.0 (2026/XX/XX) +Changes in Version 4.20.1 (2026/XX/XX) +-------------------------------------- + +Version 4.20.1 is a bug fix release. + +Bug fixes +......... + +- Fixed a bug where ``getMore`` commands in load-balanced mode were not + retried when the server returned a retryable overload error + (`PYTHON-6262`_). + +.. _PYTHON-6262: https://jira.mongodb.org/browse/PYTHON-6262 + +Changes in Version 4.20.0 (2026/11/12) -------------------------------------- - The client handshake metadata now reports a detected coding agent in ``client.env.agent`` (`PYTHON-5929`_). +- Removed the beta ``QueryType.PREFIXPREVIEW``, ``QueryType.SUFFIXPREVIEW``, + and ``QueryType.SUBSTRINGPREVIEW`` query types. Use + :attr:`~pymongo.encryption.QueryType.PREFIX`, + :attr:`~pymongo.encryption.QueryType.SUFFIX`, and + :attr:`~pymongo.encryption.QueryType.SUBSTRING` instead (requires MongoDB + 9.0+ and pymongocrypt 1.21.0+) (`PYTHON-5959`_). +- Removed the deprecated ``text_opts`` parameter of + :meth:`~pymongo.encryption.ClientEncryption.encrypt` and + :meth:`~pymongo.asynchronous.encryption.AsyncClientEncryption.encrypt`, and + the ``TextOpts`` class. Use ``string_opts`` and + :class:`~pymongo.encryption_options.StringOpts` instead (`PYTHON-5959`_). Bug fixes ......... @@ -34,13 +59,31 @@ Bug fixes due to a CPython memory leak bug (`python/cpython#116810 `_). The bug was fixed in Python 3.12.7 and Python 3.13.1. Users of Python 3.12 and 3.13 should upgrade to at least those versions (`PYTHON-6182`_). +- Fixed a bug where ``AsyncMongoClient`` could not recover after a replica set + member removed itself from the topology with its own ``hello`` response (for + example, during a node restart): the monitor's executor cancelled its own + task, so the monitor never ran again (`PYTHON-6226`_). +- Fixed undefined behavior in the C extension's BSON buffer growth: growing + an encode buffer past 1GiB doubled a signed integer past its limit. + Over-limit encodes still raise ``ValueError`` (`PYTHON-6252`_). .. _PYTHON-5929: https://jira.mongodb.org/browse/PYTHON-5929 +.. _PYTHON-5959: https://jira.mongodb.org/browse/PYTHON-5959 .. _PYTHON-6172: https://jira.mongodb.org/browse/PYTHON-6172 .. _PYTHON-6149: https://jira.mongodb.org/browse/PYTHON-6149 .. _PYTHON-5873: https://jira.mongodb.org/browse/PYTHON-5873 .. _PYTHON-6145: https://jira.mongodb.org/browse/PYTHON-6145 .. _PYTHON-6182: https://jira.mongodb.org/browse/PYTHON-6182 +.. _PYTHON-6226: https://jira.mongodb.org/browse/PYTHON-6226 +.. _PYTHON-6252: https://jira.mongodb.org/browse/PYTHON-6252 + +Issues Resolved +............... + +See the `PyMongo 4.20.0 release notes in JIRA`_ for the list of resolved issues +in this release. + +.. _PyMongo 4.20.0 release notes in JIRA: https://jira.mongodb.org/secure/ReleaseNote.jspa?projectId=10004&version=52954 Changes in Version 4.19.0 (2026/10/14) -------------------------------------- diff --git a/drivers-evergreen-tools b/drivers-evergreen-tools index 3653a7d2bf..5d52ccdbb6 160000 --- a/drivers-evergreen-tools +++ b/drivers-evergreen-tools @@ -1 +1 @@ -Subproject commit 3653a7d2bffb0b5bdb24415b69f1df60bec9a2ef +Subproject commit 5d52ccdbb60f6e1749a71ce787c9f8f7da861b15 diff --git a/fuzz/README.md b/fuzz/README.md index 8069c0586c..464601ac06 100644 --- a/fuzz/README.md +++ b/fuzz/README.md @@ -26,9 +26,9 @@ Atheris is a `uv` dependency group. Run targets from the repository root: uv run --group fuzz python fuzz/fuzz_decode.py fuzz/regression/* ``` -Atheris publishes CPython 3.12 to 3.14 wheels for Linux x86_64 only, so the -`fuzz` group cannot install on other interpreters or platforms. Pin a -compatible interpreter where one is available, and run in a Linux x86_64 +The latest atheris publishes CPython 3.12 to 3.14 wheels for Linux x86_64 +only, so the `fuzz` group may not install on other interpreters or platforms. +Pin a compatible interpreter where one is available, and run in a Linux x86_64 container otherwise: ```bash @@ -95,6 +95,34 @@ after the corpus directory. The `Failed to find function __sanitizer_*` startup warnings are benign libFuzzer symbol probes on uninstrumented runs; native ASan-instrumented fuzzing is tracked separately (PYTHON-6169). +### Captured corpus (nightly) + +The nightly run seeds from the spec seed corpus plus every unit in +`corpus/`, and libFuzzer writes each coverage-increasing ("interesting") +input it discovers back into its corpus directory. After the targets +finish, the `fuzz` task captures those new units, replays them through +every target once so a unit that fails any target is never published (it +stays in `fuzz-scratch/` for triage), and opens an automated +"[Fuzz Corpus]" PR against main (PYTHON-6178). Later nights +build on prior discoveries instead of restarting from the spec seeds. + +Growth is bounded by per-unit and per-run caps, overridable on Evergreen: + +- `FUZZ_CORPUS_MAX_UNIT_BYTES` (default 65536): skip units larger than this. +- `FUZZ_CORPUS_MAX_UNITS` (default 50): keep at most this many new units + per run, smallest first. + +Units over a cap are discarded, not deferred: they are never persisted, so +the fuzzer may re-derive them on later nights. A run that finds nothing new +opens no PR. The capture deduplicates against `main` only, so while a +`[Fuzz Corpus]` PR is open, later nights can re-capture its still-pending +units and the PRs overlap until one merges (digest-named files keep that +conflict-free). Crashing inputs are excluded: +they land in `fuzz-scratch/` as `crash-*` artifacts and follow the +`regression/` triage flow above. Corpus entries are fuzzer-generated +inputs, not code: skim the PR for size and for inputs that look like a +bug rather than a plain coverage gain before merging. + ## Coverage report Measure which lines the seed corpus reaches: @@ -113,9 +141,11 @@ gives atheris a graceful exit so coverage.py can flush its report. ``` build_corpus.py Seed corpus builder (mirrors the Go driver's build-oss-fuzz-corpus) +capture_corpus.py Nightly capture of new coverage-increasing inputs (PYTHON-6178) fuzz_decode.py Fuzz target: bson.decode() fuzz_decode_all.py Fuzz target: bson.decode_all() fuzz_is_valid.py Fuzz target: bson.is_valid() fuzz_shared.py Code shared by the fuzz targets +corpus/ Captured coverage-increasing inputs; grown by automated nightly PRs regression/ Known bug reproducers; run with the seed corpus on PRs ``` diff --git a/fuzz/build_corpus.py b/fuzz/build_corpus.py index 4d46140803..4af9bde925 100755 --- a/fuzz/build_corpus.py +++ b/fuzz/build_corpus.py @@ -144,7 +144,8 @@ def seed_boundary_documents(zw: zipfile.ZipFile) -> None: def seed_large_document(zw: zipfile.ZipFile) -> None: """Seed one ~500 KB document; without it, libFuzzer's max_len default - keeps mutation below the size where large-input paths live.""" + keeps mutation below the size where large-input paths live. + """ doc = { "long_string": "a" * (256 * 1024), "many_fields": {f"f{i:05d}": i for i in range(5_000)}, diff --git a/fuzz/capture_corpus.py b/fuzz/capture_corpus.py new file mode 100755 index 0000000000..41c076e71c --- /dev/null +++ b/fuzz/capture_corpus.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python3 +""" +Capture coverage-increasing inputs from a finished fuzzing run (PYTHON-6178). + +Compares the scratch corpus directory (where libFuzzer writes each new +"interesting" input) against the baseline manifest written by +setup_tests.py and the committed fuzz/corpus/ contents, copies the new +units into an output directory named by their SHA-256 digests, and writes +a Markdown summary for the automated corpus PR body. + +Pure stdlib: this runs on the Evergreen nightly host after the fuzz +targets finish, and its unit tests must run everywhere (no atheris, no +bson). + +Usage: python capture_corpus.py [--corpus-dir DIR] [--baseline FILE] +""" + +from __future__ import annotations + +import argparse +import os +import shutil +from hashlib import sha256 +from pathlib import Path + +DEFAULT_CORPUS_DIR = "fuzz-scratch/corpus" +DEFAULT_EXISTING = "fuzz/corpus" +DEFAULT_OUT = "fuzz-scratch/capture" +DEFAULT_SUMMARY = "fuzz-scratch/capture-summary.md" +# Growth caps keep a runaway run from flooding the repository; both are +# overridable from Evergreen. Defaults chosen in PYTHON-6178: small inputs +# carry the most coverage per committed byte. +DEFAULT_MAX_UNITS = 50 +DEFAULT_MAX_UNIT_BYTES = 64 * 1024 + + +def digest_of(path: Path) -> str: + """The SHA-256 hex digest of a file's contents.""" + digest = sha256() + with open(path, "rb") as fp: + for chunk in iter(lambda: fp.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def digest_set(directory: Path) -> set[str]: + """Content digests of every file in directory, skipping dotfiles.""" + if not directory.is_dir(): + return set() + return { + digest_of(path) + for path in sorted(directory.iterdir()) + if path.is_file() and not path.name.startswith(".") + } + + +def read_baseline(path: Path) -> set[str]: + """Read digests from a baseline manifest (one hex digest per line).""" + if not path.is_file(): + return set() + with open(path, encoding="utf-8") as fp: + return {line.strip() for line in fp if line.strip()} + + +def run( + corpus_dir: Path, + baseline: Path, + existing: Path, + out: Path, + summary: Path, + max_units: int, + max_unit_bytes: int, +) -> int: + """Copy the new units into out/ and write the PR summary. + + Returns the number of units captured; zero means the run found + nothing new and the PR step can no-op. + """ + known = read_baseline(baseline) | digest_set(existing) + + # Sorted (size, digest, path): the size key prefers the smallest + # inputs when the per-run cap bites. + candidates: list[tuple[int, str, Path]] = [] + oversize = 0 + for path in sorted(corpus_dir.iterdir()): + if path.name.startswith(".") or not path.is_file(): + continue + digest = digest_of(path) + if digest in known: + continue + # Track accepted digests: same contents under two names count once. + known.add(digest) + size = path.stat().st_size + if size > max_unit_bytes: + oversize += 1 + continue + candidates.append((size, digest, path)) + candidates.sort() + + kept = candidates[:max_units] + over_cap = len(candidates) - len(kept) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + for _, digest, path in kept: + shutil.copyfile(path, out / digest) + + write_summary(summary, kept, oversize, over_cap, max_units, max_unit_bytes) + print( + f"Captured {len(kept)} new units " + f"({oversize} oversize skipped, {over_cap} over the per-run cap)." + ) + return len(kept) + + +def write_summary( + path: Path, + kept: list[tuple[int, str, Path]], + oversize: int, + over_cap: int, + max_units: int, + max_unit_bytes: int, +) -> None: + """Write the Markdown capture summary used as the automated PR body.""" + lines = [ + "Captured coverage-increasing inputs from last night's BSON fuzz run.", + "", + f"- New units added: **{len(kept)}**", + f"- Units skipped over the per-unit cap ({max_unit_bytes} bytes): {oversize}", + f"- Units dropped over the per-run cap ({max_units}): {over_cap}", + "", + ( + "These are fuzzer-generated inputs, not reviewed code. Before merging, " + "skim them for size and for inputs that look like a bug rather than a " + "plain coverage gain; anything crashing belongs in `fuzz/regression/`." + ), + ] + if kept: + lines.extend(["", "Largest units added:"]) + for size, digest, _ in sorted(kept, reverse=True)[:5]: + lines.append(f"- `{digest[:16]}` ({size} bytes)") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Capture new coverage-increasing inputs from a fuzz run." + ) + parser.add_argument( + "--corpus-dir", + default=os.environ.get("FUZZ_CORPUS_DIR", DEFAULT_CORPUS_DIR), + ) + parser.add_argument( + "--baseline", + default=None, + help="Digest manifest; defaults to baseline.txt next to the corpus dir.", + ) + parser.add_argument("--existing", default=DEFAULT_EXISTING) + parser.add_argument("--out", default=DEFAULT_OUT) + parser.add_argument("--summary", default=DEFAULT_SUMMARY) + parser.add_argument( + "--max-units", + type=int, + default=int(os.environ.get("FUZZ_CORPUS_MAX_UNITS", DEFAULT_MAX_UNITS)), + ) + parser.add_argument( + "--max-unit-bytes", + type=int, + default=int(os.environ.get("FUZZ_CORPUS_MAX_UNIT_BYTES", DEFAULT_MAX_UNIT_BYTES)), + ) + args = parser.parse_args() + # Negative or zero caps are operator error (e.g. a mis-set Evergreen + # expansion): fail with an actionable message rather than a nonsense + # keep-set like "all but the last N". + if args.max_units < 1: + parser.error("--max-units must be at least 1") + if args.max_unit_bytes < 1: + parser.error("--max-unit-bytes must be at least 1") + corpus_dir = Path(args.corpus_dir) + baseline = Path(args.baseline) if args.baseline else corpus_dir.parent / "baseline.txt" + run( + corpus_dir=corpus_dir, + baseline=baseline, + existing=Path(args.existing), + out=Path(args.out), + summary=Path(args.summary), + max_units=args.max_units, + max_unit_bytes=args.max_unit_bytes, + ) + + +if __name__ == "__main__": + main() diff --git a/fuzz/corpus/.gitkeep b/fuzz/corpus/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/fuzz/fuzz_decode.py b/fuzz/fuzz_decode.py index b323c97092..261059b349 100755 --- a/fuzz/fuzz_decode.py +++ b/fuzz/fuzz_decode.py @@ -8,8 +8,6 @@ from __future__ import annotations -from typing import Optional - import atheris from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize @@ -25,7 +23,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_with(bson_mod, data: bytes) -> Optional[dict]: +def _decode_with(bson_mod, data: bytes) -> dict | None: """Run bson_mod.decode(data), returning the document or None on expected errors.""" try: return bson_mod.decode(data) diff --git a/fuzz/fuzz_decode_all.py b/fuzz/fuzz_decode_all.py index fa01549607..e8a9812fc6 100755 --- a/fuzz/fuzz_decode_all.py +++ b/fuzz/fuzz_decode_all.py @@ -8,8 +8,6 @@ from __future__ import annotations -from typing import Optional - import atheris from fuzz_shared import OTHER_ERRORS, load_pure_python_bson, main, normalize @@ -25,7 +23,7 @@ _BOTH_IMPLS = _bson_c.has_c() -def _decode_all_with(bson_mod, data: bytes) -> Optional[list]: +def _decode_all_with(bson_mod, data: bytes) -> list | None: """Run bson_mod.decode_all(data), returning the documents or None on expected errors.""" try: return bson_mod.decode_all(data) diff --git a/gridfs/asynchronous/grid_file.py b/gridfs/asynchronous/grid_file.py index f3d816f4dd..b601b8338b 100644 --- a/gridfs/asynchronous/grid_file.py +++ b/gridfs/asynchronous/grid_file.py @@ -21,8 +21,7 @@ import io import math from collections import abc -from collections.abc import Iterable, Mapping -from typing import Any, NoReturn, Optional, cast +from typing import TYPE_CHECKING, Any, NoReturn, Self, cast from bson.int64 import Int64 from bson.objectid import ObjectId @@ -44,7 +43,6 @@ _clear_entity_type_registry, ) from pymongo import ASCENDING, DESCENDING, WriteConcern, _csot -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.cursor import AsyncCursor from pymongo.asynchronous.database import AsyncDatabase @@ -61,10 +59,16 @@ from pymongo.helpers_shared import _check_write_command_response from pymongo.read_preferences import ReadPreference, _ServerMode +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + from types import TracebackType + + from pymongo.asynchronous.client_session import AsyncClientSession + _IS_SYNC = False -def _disallow_transactions(session: Optional[AsyncClientSession]) -> None: +def _disallow_transactions(session: AsyncClientSession | None) -> None: if session and session.in_transaction: raise InvalidOperation("GridFS does not support multi-document transactions") @@ -158,7 +162,7 @@ async def put(self, data: Any, **kwargs: Any) -> Any: await grid_file.write(data) return grid_file._id - async def get(self, file_id: Any, session: Optional[AsyncClientSession] = None) -> AsyncGridOut: + async def get(self, file_id: Any, session: AsyncClientSession | None = None) -> AsyncGridOut: """Get a file from GridFS by ``"_id"``. Returns an instance of :class:`~gridfs.grid_file.GridOut`, @@ -179,9 +183,9 @@ async def get(self, file_id: Any, session: Optional[AsyncClientSession] = None) async def get_version( self, - filename: Optional[str] = None, - version: Optional[int] = -1, - session: Optional[AsyncClientSession] = None, + filename: str | None = None, + version: int | None = -1, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> AsyncGridOut: """Get a file from GridFS by ``"filename"`` or metadata fields. @@ -238,8 +242,8 @@ async def get_version( async def get_last_version( self, - filename: Optional[str] = None, - session: Optional[AsyncClientSession] = None, + filename: str | None = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> AsyncGridOut: """Get the most recent version of a file in GridFS by ``"filename"`` @@ -259,7 +263,7 @@ async def get_last_version( return await self.get_version(filename=filename, session=session, **kwargs) # TODO add optional safe mode for chunk removal? - async def delete(self, file_id: Any, session: Optional[AsyncClientSession] = None) -> None: + async def delete(self, file_id: Any, session: AsyncClientSession | None = None) -> None: """Delete a file from GridFS by ``"_id"``. Deletes all data belonging to the file with ``"_id"``: @@ -287,7 +291,7 @@ async def delete(self, file_id: Any, session: Optional[AsyncClientSession] = Non await self._files.delete_one({"_id": {"$eq": file_id}}, session=session) await self._chunks.delete_many({"files_id": {"$eq": file_id}}, session=session) - async def list(self, session: Optional[AsyncClientSession] = None) -> list[str]: + async def list(self, session: AsyncClientSession | None = None) -> list[str]: """List the names of all files stored in this instance of :class:`GridFS`. @@ -311,11 +315,11 @@ async def list(self, session: Optional[AsyncClientSession] = None) -> list[str]: async def find_one( self, - filter: Optional[Any] = None, - session: Optional[AsyncClientSession] = None, + filter: Any | None = None, + session: AsyncClientSession | None = None, *args: Any, **kwargs: Any, - ) -> Optional[AsyncGridOut]: + ) -> AsyncGridOut | None: """Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for @@ -411,8 +415,8 @@ def find(self, *args: Any, **kwargs: Any) -> AsyncGridOutCursor: async def exists( self, - document_or_id: Optional[Any] = None, - session: Optional[AsyncClientSession] = None, + document_or_id: Any | None = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> bool: """Check if a file exists in this instance of :class:`GridFS`. @@ -470,8 +474,8 @@ def __init__( db: AsyncDatabase[Any], bucket_name: str = "fs", chunk_size_bytes: int = DEFAULT_CHUNK_SIZE, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, ) -> None: """Create a new instance of :class:`GridFSBucket`. @@ -531,9 +535,9 @@ def __init__( def open_upload_stream( self, filename: str, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[AsyncClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: AsyncClientSession | None = None, ) -> AsyncGridIn: """Opens a Stream that the application can write the contents of the file to. @@ -586,9 +590,9 @@ def open_upload_stream_with_id( self, file_id: Any, filename: str, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[AsyncClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: AsyncClientSession | None = None, ) -> AsyncGridIn: """Opens a Stream that the application can write the contents of the file to. @@ -647,9 +651,9 @@ async def upload_from_stream( self, filename: str, source: Any, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[AsyncClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: AsyncClientSession | None = None, ) -> ObjectId: """Uploads a user file to a GridFS bucket. @@ -690,7 +694,7 @@ async def upload_from_stream( ) as gin: await gin.write(source) - return cast(ObjectId, gin._id) + return cast("ObjectId", gin._id) @_csot.apply async def upload_from_stream_with_id( @@ -698,9 +702,9 @@ async def upload_from_stream_with_id( file_id: Any, filename: str, source: Any, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[AsyncClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: AsyncClientSession | None = None, ) -> None: """Uploads a user file to a GridFS bucket with a custom file id. @@ -743,7 +747,7 @@ async def upload_from_stream_with_id( await gin.write(source) async def open_download_stream( - self, file_id: Any, session: Optional[AsyncClientSession] = None + self, file_id: Any, session: AsyncClientSession | None = None ) -> AsyncGridOut: """Opens a Stream from which the application can read the contents of the stored file specified by file_id. @@ -776,7 +780,7 @@ async def open_download_stream( @_csot.apply async def download_to_stream( - self, file_id: Any, destination: Any, session: Optional[AsyncClientSession] = None + self, file_id: Any, destination: Any, session: AsyncClientSession | None = None ) -> None: """Downloads the contents of the stored file specified by file_id and writes the contents to `destination`. @@ -811,7 +815,7 @@ async def download_to_stream( destination.write(chunk) @_csot.apply - async def delete(self, file_id: Any, session: Optional[AsyncClientSession] = None) -> None: + async def delete(self, file_id: Any, session: AsyncClientSession | None = None) -> None: """Given an file_id, delete this stored file's files collection document and associated chunks from a GridFS bucket. @@ -840,7 +844,7 @@ async def delete(self, file_id: Any, session: Optional[AsyncClientSession] = Non @_csot.apply async def delete_by_name( - self, filename: str, session: Optional[AsyncClientSession] = None + self, filename: str, session: AsyncClientSession | None = None ) -> None: """Given a filename, delete this stored file's files collection document(s) and associated chunks from a GridFS bucket. @@ -915,7 +919,7 @@ def find(self, *args: Any, **kwargs: Any) -> AsyncGridOutCursor: return AsyncGridOutCursor(self._collection, *args, **kwargs) async def open_download_stream_by_name( - self, filename: str, revision: int = -1, session: Optional[AsyncClientSession] = None + self, filename: str, revision: int = -1, session: AsyncClientSession | None = None ) -> AsyncGridOut: """Opens a Stream from which the application can read the contents of `filename` and optional `revision`. @@ -974,7 +978,7 @@ async def download_to_stream_by_name( filename: str, destination: Any, revision: int = -1, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, ) -> None: """Write the contents of `filename` (with optional `revision`) to `destination`. @@ -1022,7 +1026,7 @@ async def download_to_stream_by_name( destination.write(chunk) async def rename( - self, file_id: Any, new_filename: str, session: Optional[AsyncClientSession] = None + self, file_id: Any, new_filename: str, session: AsyncClientSession | None = None ) -> None: """Renames the stored file with the specified file_id. @@ -1054,7 +1058,7 @@ async def rename( ) async def rename_by_name( - self, filename: str, new_filename: str, session: Optional[AsyncClientSession] = None + self, filename: str, new_filename: str, session: AsyncClientSession | None = None ) -> None: """Renames the stored file with the specified filename. @@ -1089,7 +1093,7 @@ class AsyncGridIn: def __init__( self, root_collection: AsyncCollection[Any], - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> None: """Write a file to GridFS @@ -1214,9 +1218,9 @@ def closed(self) -> bool: return self._closed _id: Any = _a_grid_in_property("_id", "The ``'_id'`` value for this file.", read_only=True) - filename: Optional[str] = _a_grid_in_property("filename", "Name of this file.") - name: Optional[str] = _a_grid_in_property("filename", "Alias for `filename`.") - content_type: Optional[str] = _a_grid_in_property( + filename: str | None = _a_grid_in_property("filename", "Name of this file.") + name: str | None = _a_grid_in_property("filename", "Alias for `filename`.") + content_type: str | None = _a_grid_in_property( "contentType", "DEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file." ) length: int = _a_grid_in_property("length", "Length (in bytes) of this file.", closed_only=True) @@ -1224,7 +1228,7 @@ def closed(self) -> bool: upload_date: datetime.datetime = _a_grid_in_property( "uploadDate", "Date that this file was uploaded.", closed_only=True ) - md5: Optional[str] = _a_grid_in_property( + md5: str | None = _a_grid_in_property( "md5", "DEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.", closed_only=True, @@ -1438,11 +1442,16 @@ async def writelines(self, sequence: Iterable[Any]) -> None: def writeable(self) -> bool: return True - async def __aenter__(self) -> AsyncGridIn: + async def __aenter__(self) -> Self: """Support for the context manager protocol.""" return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> Any: """Support for the context manager protocol. Close the file if no exceptions occur and allow exceptions to propagate. @@ -1467,9 +1476,9 @@ class AsyncGridOut(GRIDOUT_BASE_CLASS): # type: ignore def __init__( self, root_collection: AsyncCollection[Any], - file_id: Optional[int] = None, - file_document: Optional[Any] = None, - session: Optional[AsyncClientSession] = None, + file_id: int | None = None, + file_document: Any | None = None, + session: AsyncClientSession | None = None, ) -> None: """Read a file from GridFS @@ -1529,7 +1538,7 @@ def __init__( _id: Any = _a_grid_out_property("_id", "The ``'_id'`` value for this file.") filename: str = _a_grid_out_property("filename", "Name of this file.") name: str = _a_grid_out_property("filename", "Alias for `filename`.") - content_type: Optional[str] = _a_grid_out_property( + content_type: str | None = _a_grid_out_property( "contentType", "DEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file." ) length: int = _a_grid_out_property("length", "Length (in bytes) of this file.") @@ -1537,13 +1546,13 @@ def __init__( upload_date: datetime.datetime = _a_grid_out_property( "uploadDate", "Date that this file was first uploaded." ) - aliases: Optional[list[str]] = _a_grid_out_property( + aliases: list[str] | None = _a_grid_out_property( "aliases", "DEPRECATED, will be removed in PyMongo 5.0. List of aliases for this file." ) - metadata: Optional[Mapping[str, Any]] = _a_grid_out_property( + metadata: Mapping[str, Any] | None = _a_grid_out_property( "metadata", "Metadata attached to this file." ) - md5: Optional[str] = _a_grid_out_property( + md5: str | None = _a_grid_out_property( "md5", "DEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.", ) @@ -1757,9 +1766,9 @@ def seekable(self) -> bool: return True def __aiter__(self) -> AsyncGridOut: - """Return an iterator over all of this file's data. + r"""Return an iterator over all of this file's data. - The iterator will return lines (delimited by ``b'\\n'``) of + The iterator will return lines (delimited by ``b'\n'``) of :class:`bytes`. This can be useful when serving files using a webserver that handles such an iterator efficiently. @@ -1796,13 +1805,18 @@ def writelines(self, lines: Any) -> NoReturn: def writable(self) -> bool: return False - async def __aenter__(self) -> AsyncGridOut: + async def __aenter__(self) -> Self: """Makes it possible to use :class:`AsyncGridOut` files with the async context manager protocol. """ return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> Any: """Makes it possible to use :class:`AsyncGridOut` files with the async context manager protocol. """ @@ -1819,7 +1833,7 @@ def flush(self) -> None: def isatty(self) -> bool: return False - def truncate(self, size: Optional[int] = None) -> NoReturn: + def truncate(self, size: int | None = None) -> NoReturn: # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to raise. raise io.UnsupportedOperation("truncate") @@ -1842,7 +1856,7 @@ def __init__( self, grid_out: AsyncGridOut, chunks: AsyncCollection[Any], - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, next_chunk: Any, ) -> None: self._id = grid_out._id @@ -1854,7 +1868,7 @@ def __init__( self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor = None - _cursor: Optional[AsyncCursor[Any]] + _cursor: AsyncCursor[Any] | None def expected_chunk_length(self, chunk_n: int) -> int: if chunk_n < self._num_chunks - 1: @@ -1955,13 +1969,13 @@ class AsyncGridOutCursor(AsyncCursor): # type: ignore[type-arg] def __init__( self, collection: AsyncCollection[Any], - filter: Optional[Mapping[str, Any]] = None, + filter: Mapping[str, Any] | None = None, skip: int = 0, limit: int = 0, no_cursor_timeout: bool = False, - sort: Optional[Any] = None, + sort: Any | None = None, batch_size: int = 0, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, ) -> None: """Create a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. @@ -1996,16 +2010,13 @@ async def next(self) -> AsyncGridOut: next_file = await super().next() return AsyncGridOut(self._root_collection, file_document=next_file, session=self.session) - async def to_list(self, length: Optional[int] = None) -> list[AsyncGridOut]: + async def to_list(self, length: int | None = None) -> list[AsyncGridOut]: """Convert the cursor to a list.""" if length is None: return [x async for x in self] # noqa: C416,RUF100 if length < 1: raise ValueError("to_list() length must be greater than 0") - ret = [] - for _ in range(length): - ret.append(await self.next()) - return ret + return [await self.next() for _ in range(length)] __anext__ = next @@ -2015,6 +2026,6 @@ def add_option(self, *args: Any, **kwargs: Any) -> NoReturn: def remove_option(self, *args: Any, **kwargs: Any) -> NoReturn: raise NotImplementedError("Method does not exist for GridOutCursor") - def _clone_base(self, session: Optional[AsyncClientSession]) -> AsyncGridOutCursor: + def _clone_base(self, session: AsyncClientSession | None) -> AsyncGridOutCursor: """Creates an empty GridOutCursor for information to be copied into.""" return AsyncGridOutCursor(self._root_collection, session=session) diff --git a/gridfs/grid_file_shared.py b/gridfs/grid_file_shared.py index 470f3f14d2..f75a350d24 100644 --- a/gridfs/grid_file_shared.py +++ b/gridfs/grid_file_shared.py @@ -2,7 +2,7 @@ import os import warnings -from typing import Any, Optional +from typing import Any from pymongo import ASCENDING from pymongo.common import MAX_MESSAGE_SIZE @@ -33,11 +33,10 @@ def _a_grid_in_property( field_name: str, docstring: str, - read_only: Optional[bool] = False, - closed_only: Optional[bool] = False, + read_only: bool | None = False, + closed_only: bool | None = False, ) -> Any: """Create a GridIn property.""" - warn_str = "" if docstring.startswith("DEPRECATED,"): warn_str = ( @@ -96,8 +95,8 @@ def a_getter(self: Any) -> Any: def _grid_in_property( field_name: str, docstring: str, - read_only: Optional[bool] = False, - closed_only: Optional[bool] = False, + read_only: bool | None = False, + closed_only: bool | None = False, ) -> Any: """Create a GridIn property.""" warn_str = "" diff --git a/gridfs/synchronous/grid_file.py b/gridfs/synchronous/grid_file.py index ac7301e170..52b4caaa28 100644 --- a/gridfs/synchronous/grid_file.py +++ b/gridfs/synchronous/grid_file.py @@ -21,8 +21,7 @@ import io import math from collections import abc -from collections.abc import Iterable, Mapping -from typing import Any, NoReturn, Optional, cast +from typing import TYPE_CHECKING, Any, NoReturn, Self, cast from bson.int64 import Int64 from bson.objectid import ObjectId @@ -55,16 +54,21 @@ ) from pymongo.helpers_shared import _check_write_command_response from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.cursor import Cursor from pymongo.synchronous.database import Database from pymongo.synchronous.helpers import next +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + from types import TracebackType + + from pymongo.synchronous.client_session import ClientSession + _IS_SYNC = True -def _disallow_transactions(session: Optional[ClientSession]) -> None: +def _disallow_transactions(session: ClientSession | None) -> None: if session and session.in_transaction: raise InvalidOperation("GridFS does not support multi-document transactions") @@ -158,7 +162,7 @@ def put(self, data: Any, **kwargs: Any) -> Any: grid_file.write(data) return grid_file._id - def get(self, file_id: Any, session: Optional[ClientSession] = None) -> GridOut: + def get(self, file_id: Any, session: ClientSession | None = None) -> GridOut: """Get a file from GridFS by ``"_id"``. Returns an instance of :class:`~gridfs.grid_file.GridOut`, @@ -179,9 +183,9 @@ def get(self, file_id: Any, session: Optional[ClientSession] = None) -> GridOut: def get_version( self, - filename: Optional[str] = None, - version: Optional[int] = -1, - session: Optional[ClientSession] = None, + filename: str | None = None, + version: int | None = -1, + session: ClientSession | None = None, **kwargs: Any, ) -> GridOut: """Get a file from GridFS by ``"filename"`` or metadata fields. @@ -238,8 +242,8 @@ def get_version( def get_last_version( self, - filename: Optional[str] = None, - session: Optional[ClientSession] = None, + filename: str | None = None, + session: ClientSession | None = None, **kwargs: Any, ) -> GridOut: """Get the most recent version of a file in GridFS by ``"filename"`` @@ -259,7 +263,7 @@ def get_last_version( return self.get_version(filename=filename, session=session, **kwargs) # TODO add optional safe mode for chunk removal? - def delete(self, file_id: Any, session: Optional[ClientSession] = None) -> None: + def delete(self, file_id: Any, session: ClientSession | None = None) -> None: """Delete a file from GridFS by ``"_id"``. Deletes all data belonging to the file with ``"_id"``: @@ -287,7 +291,7 @@ def delete(self, file_id: Any, session: Optional[ClientSession] = None) -> None: self._files.delete_one({"_id": {"$eq": file_id}}, session=session) self._chunks.delete_many({"files_id": {"$eq": file_id}}, session=session) - def list(self, session: Optional[ClientSession] = None) -> list[str]: + def list(self, session: ClientSession | None = None) -> list[str]: """List the names of all files stored in this instance of :class:`GridFS`. @@ -309,11 +313,11 @@ def list(self, session: Optional[ClientSession] = None) -> list[str]: def find_one( self, - filter: Optional[Any] = None, - session: Optional[ClientSession] = None, + filter: Any | None = None, + session: ClientSession | None = None, *args: Any, **kwargs: Any, - ) -> Optional[GridOut]: + ) -> GridOut | None: """Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for @@ -409,8 +413,8 @@ def find(self, *args: Any, **kwargs: Any) -> GridOutCursor: def exists( self, - document_or_id: Optional[Any] = None, - session: Optional[ClientSession] = None, + document_or_id: Any | None = None, + session: ClientSession | None = None, **kwargs: Any, ) -> bool: """Check if a file exists in this instance of :class:`GridFS`. @@ -468,8 +472,8 @@ def __init__( db: Database[Any], bucket_name: str = "fs", chunk_size_bytes: int = DEFAULT_CHUNK_SIZE, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, ) -> None: """Create a new instance of :class:`GridFSBucket`. @@ -529,9 +533,9 @@ def __init__( def open_upload_stream( self, filename: str, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[ClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: ClientSession | None = None, ) -> GridIn: """Opens a Stream that the application can write the contents of the file to. @@ -584,9 +588,9 @@ def open_upload_stream_with_id( self, file_id: Any, filename: str, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[ClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: ClientSession | None = None, ) -> GridIn: """Opens a Stream that the application can write the contents of the file to. @@ -645,9 +649,9 @@ def upload_from_stream( self, filename: str, source: Any, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[ClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: ClientSession | None = None, ) -> ObjectId: """Uploads a user file to a GridFS bucket. @@ -686,7 +690,7 @@ def upload_from_stream( with self.open_upload_stream(filename, chunk_size_bytes, metadata, session=session) as gin: gin.write(source) - return cast(ObjectId, gin._id) + return cast("ObjectId", gin._id) @_csot.apply def upload_from_stream_with_id( @@ -694,9 +698,9 @@ def upload_from_stream_with_id( file_id: Any, filename: str, source: Any, - chunk_size_bytes: Optional[int] = None, - metadata: Optional[Mapping[str, Any]] = None, - session: Optional[ClientSession] = None, + chunk_size_bytes: int | None = None, + metadata: Mapping[str, Any] | None = None, + session: ClientSession | None = None, ) -> None: """Uploads a user file to a GridFS bucket with a custom file id. @@ -738,9 +742,7 @@ def upload_from_stream_with_id( ) as gin: gin.write(source) - def open_download_stream( - self, file_id: Any, session: Optional[ClientSession] = None - ) -> GridOut: + def open_download_stream(self, file_id: Any, session: ClientSession | None = None) -> GridOut: """Opens a Stream from which the application can read the contents of the stored file specified by file_id. @@ -772,7 +774,7 @@ def open_download_stream( @_csot.apply def download_to_stream( - self, file_id: Any, destination: Any, session: Optional[ClientSession] = None + self, file_id: Any, destination: Any, session: ClientSession | None = None ) -> None: """Downloads the contents of the stored file specified by file_id and writes the contents to `destination`. @@ -807,7 +809,7 @@ def download_to_stream( destination.write(chunk) @_csot.apply - def delete(self, file_id: Any, session: Optional[ClientSession] = None) -> None: + def delete(self, file_id: Any, session: ClientSession | None = None) -> None: """Given an file_id, delete this stored file's files collection document and associated chunks from a GridFS bucket. @@ -835,7 +837,7 @@ def delete(self, file_id: Any, session: Optional[ClientSession] = None) -> None: raise NoFile(f"no file could be deleted because none matched {file_id}") @_csot.apply - def delete_by_name(self, filename: str, session: Optional[ClientSession] = None) -> None: + def delete_by_name(self, filename: str, session: ClientSession | None = None) -> None: """Given a filename, delete this stored file's files collection document(s) and associated chunks from a GridFS bucket. @@ -909,7 +911,7 @@ def find(self, *args: Any, **kwargs: Any) -> GridOutCursor: return GridOutCursor(self._collection, *args, **kwargs) def open_download_stream_by_name( - self, filename: str, revision: int = -1, session: Optional[ClientSession] = None + self, filename: str, revision: int = -1, session: ClientSession | None = None ) -> GridOut: """Opens a Stream from which the application can read the contents of `filename` and optional `revision`. @@ -968,7 +970,7 @@ def download_to_stream_by_name( filename: str, destination: Any, revision: int = -1, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, ) -> None: """Write the contents of `filename` (with optional `revision`) to `destination`. @@ -1013,9 +1015,7 @@ def download_to_stream_by_name( break destination.write(chunk) - def rename( - self, file_id: Any, new_filename: str, session: Optional[ClientSession] = None - ) -> None: + def rename(self, file_id: Any, new_filename: str, session: ClientSession | None = None) -> None: """Renames the stored file with the specified file_id. For example:: @@ -1046,7 +1046,7 @@ def rename( ) def rename_by_name( - self, filename: str, new_filename: str, session: Optional[ClientSession] = None + self, filename: str, new_filename: str, session: ClientSession | None = None ) -> None: """Renames the stored file with the specified filename. @@ -1081,7 +1081,7 @@ class GridIn: def __init__( self, root_collection: Collection[Any], - session: Optional[ClientSession] = None, + session: ClientSession | None = None, **kwargs: Any, ) -> None: """Write a file to GridFS @@ -1200,9 +1200,9 @@ def closed(self) -> bool: return self._closed _id: Any = _grid_in_property("_id", "The ``'_id'`` value for this file.", read_only=True) - filename: Optional[str] = _grid_in_property("filename", "Name of this file.") - name: Optional[str] = _grid_in_property("filename", "Alias for `filename`.") - content_type: Optional[str] = _grid_in_property( + filename: str | None = _grid_in_property("filename", "Name of this file.") + name: str | None = _grid_in_property("filename", "Alias for `filename`.") + content_type: str | None = _grid_in_property( "contentType", "DEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file." ) length: int = _grid_in_property("length", "Length (in bytes) of this file.", closed_only=True) @@ -1210,7 +1210,7 @@ def closed(self) -> bool: upload_date: datetime.datetime = _grid_in_property( "uploadDate", "Date that this file was uploaded.", closed_only=True ) - md5: Optional[str] = _grid_in_property( + md5: str | None = _grid_in_property( "md5", "DEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.", closed_only=True, @@ -1424,11 +1424,16 @@ def writelines(self, sequence: Iterable[Any]) -> None: def writeable(self) -> bool: return True - def __enter__(self) -> GridIn: + def __enter__(self) -> Self: """Support for the context manager protocol.""" return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> Any: """Support for the context manager protocol. Close the file if no exceptions occur and allow exceptions to propagate. @@ -1453,9 +1458,9 @@ class GridOut(GRIDOUT_BASE_CLASS): # type: ignore def __init__( self, root_collection: Collection[Any], - file_id: Optional[int] = None, - file_document: Optional[Any] = None, - session: Optional[ClientSession] = None, + file_id: int | None = None, + file_document: Any | None = None, + session: ClientSession | None = None, ) -> None: """Read a file from GridFS @@ -1515,7 +1520,7 @@ def __init__( _id: Any = _grid_out_property("_id", "The ``'_id'`` value for this file.") filename: str = _grid_out_property("filename", "Name of this file.") name: str = _grid_out_property("filename", "Alias for `filename`.") - content_type: Optional[str] = _grid_out_property( + content_type: str | None = _grid_out_property( "contentType", "DEPRECATED, will be removed in PyMongo 5.0. Mime-type for this file." ) length: int = _grid_out_property("length", "Length (in bytes) of this file.") @@ -1523,13 +1528,13 @@ def __init__( upload_date: datetime.datetime = _grid_out_property( "uploadDate", "Date that this file was first uploaded." ) - aliases: Optional[list[str]] = _grid_out_property( + aliases: list[str] | None = _grid_out_property( "aliases", "DEPRECATED, will be removed in PyMongo 5.0. List of aliases for this file." ) - metadata: Optional[Mapping[str, Any]] = _grid_out_property( + metadata: Mapping[str, Any] | None = _grid_out_property( "metadata", "Metadata attached to this file." ) - md5: Optional[str] = _grid_out_property( + md5: str | None = _grid_out_property( "md5", "DEPRECATED, will be removed in PyMongo 5.0. MD5 of the contents of this file if an md5 sum was created.", ) @@ -1743,9 +1748,9 @@ def seekable(self) -> bool: return True def __iter__(self) -> GridOut: - """Return an iterator over all of this file's data. + r"""Return an iterator over all of this file's data. - The iterator will return lines (delimited by ``b'\\n'``) of + The iterator will return lines (delimited by ``b'\n'``) of :class:`bytes`. This can be useful when serving files using a webserver that handles such an iterator efficiently. @@ -1782,13 +1787,18 @@ def writelines(self, lines: Any) -> NoReturn: def writable(self) -> bool: return False - def __enter__(self) -> GridOut: + def __enter__(self) -> Self: """Makes it possible to use :class:`GridOut` files with the async context manager protocol. """ return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> Any: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> Any: """Makes it possible to use :class:`GridOut` files with the async context manager protocol. """ @@ -1805,7 +1815,7 @@ def flush(self) -> None: def isatty(self) -> bool: return False - def truncate(self, size: Optional[int] = None) -> NoReturn: + def truncate(self, size: int | None = None) -> NoReturn: # See https://docs.python.org/3/library/io.html#io.IOBase.writable # for why truncate has to raise. raise io.UnsupportedOperation("truncate") @@ -1828,7 +1838,7 @@ def __init__( self, grid_out: GridOut, chunks: Collection[Any], - session: Optional[ClientSession], + session: ClientSession | None, next_chunk: Any, ) -> None: self._id = grid_out._id @@ -1840,7 +1850,7 @@ def __init__( self._num_chunks = math.ceil(float(self._length) / self._chunk_size) self._cursor = None - _cursor: Optional[Cursor[Any]] + _cursor: Cursor[Any] | None def expected_chunk_length(self, chunk_n: int) -> int: if chunk_n < self._num_chunks - 1: @@ -1939,13 +1949,13 @@ class GridOutCursor(Cursor): # type: ignore[type-arg] def __init__( self, collection: Collection[Any], - filter: Optional[Mapping[str, Any]] = None, + filter: Mapping[str, Any] | None = None, skip: int = 0, limit: int = 0, no_cursor_timeout: bool = False, - sort: Optional[Any] = None, + sort: Any | None = None, batch_size: int = 0, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, ) -> None: """Create a new cursor, similar to the normal :class:`~pymongo.cursor.Cursor`. @@ -1980,16 +1990,13 @@ def next(self) -> GridOut: next_file = super().next() return GridOut(self._root_collection, file_document=next_file, session=self.session) - def to_list(self, length: Optional[int] = None) -> list[GridOut]: + def to_list(self, length: int | None = None) -> list[GridOut]: """Convert the cursor to a list.""" if length is None: return [x for x in self] # noqa: C416,RUF100 if length < 1: raise ValueError("to_list() length must be greater than 0") - ret = [] - for _ in range(length): - ret.append(self.next()) - return ret + return [self.next() for _ in range(length)] __next__ = next @@ -1999,6 +2006,6 @@ def add_option(self, *args: Any, **kwargs: Any) -> NoReturn: def remove_option(self, *args: Any, **kwargs: Any) -> NoReturn: raise NotImplementedError("Method does not exist for GridOutCursor") - def _clone_base(self, session: Optional[ClientSession]) -> GridOutCursor: + def _clone_base(self, session: ClientSession | None) -> GridOutCursor: """Creates an empty GridOutCursor for information to be copied into.""" return GridOutCursor(self._root_collection, session=session) diff --git a/pymongo/__init__.py b/pymongo/__init__.py index dac07ce184..ee8997f1b4 100644 --- a/pymongo/__init__.py +++ b/pymongo/__init__.py @@ -16,9 +16,6 @@ from __future__ import annotations -from contextlib import AbstractContextManager -from typing import Optional - __all__ = [ "ASCENDING", "DESCENDING", @@ -115,13 +112,17 @@ from pymongo import collection # noqa: F401 from pymongo import command_cursor # noqa: F401 from pymongo import database # noqa: F401 +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from contextlib import AbstractContextManager # isort: on version = __version__ """Current version of PyMongo.""" -def timeout(seconds: Optional[float]) -> AbstractContextManager[None]: +def timeout(seconds: float | None) -> AbstractContextManager[None]: """**(Provisional)** Apply the given timeout for a block of operations. .. note:: :func:`~pymongo.timeout` is currently provisional. Backwards diff --git a/pymongo/_asyncio_lock.py b/pymongo/_asyncio_lock.py index cde1b0ca51..18d97e6beb 100644 --- a/pymongo/_asyncio_lock.py +++ b/pymongo/_asyncio_lock.py @@ -2,15 +2,19 @@ """Lock and Condition classes vendored from https://github.com/python/cpython/blob/main/Lib/asyncio/locks.py to port 3.13 fixes to older versions of Python. -Can be removed once we drop Python 3.12 support.""" +Can be removed once we drop Python 3.12 support. +""" from __future__ import annotations import collections import threading from asyncio import events, exceptions -from collections.abc import Coroutine -from typing import Any, Optional +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Coroutine + from types import TracebackType _global_lock = threading.Lock() @@ -37,7 +41,12 @@ async def __aenter__(self) -> None: # statement for locks. return - async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: self.release() # type: ignore[attr-defined] @@ -94,7 +103,7 @@ class Lock(_ContextManagerMixin, _LoopBoundMixin): """ def __init__(self) -> None: - self._waiters: Optional[collections.deque[Any]] = None + self._waiters: collections.deque[Any] | None = None self._locked = False def __repr__(self) -> str: @@ -187,7 +196,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): A new Lock object is created and used as the underlying lock. """ - def __init__(self, lock: Optional[Lock] = None) -> None: + def __init__(self, lock: Lock | None = None) -> None: if lock is None: lock = Lock() diff --git a/pymongo/_azure_helpers.py b/pymongo/_azure_helpers.py index 231625d8d7..6b96e48fbf 100644 --- a/pymongo/_azure_helpers.py +++ b/pymongo/_azure_helpers.py @@ -17,12 +17,12 @@ from __future__ import annotations import json -from typing import Any, Optional +from typing import Any from urllib.parse import quote def _get_azure_response( - resource: str, client_id: Optional[str] = None, timeout: float = 5 + resource: str, client_id: str | None = None, timeout: float = 5 ) -> dict[str, Any]: # Deferred import to save overall import time. from urllib.request import Request, urlopen diff --git a/pymongo/_client_bulk_shared.py b/pymongo/_client_bulk_shared.py index 0019d0c0bb..fdb40a25c6 100644 --- a/pymongo/_client_bulk_shared.py +++ b/pymongo/_client_bulk_shared.py @@ -17,8 +17,7 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping -from typing import TYPE_CHECKING, Any, NoReturn, Optional, Union +from typing import TYPE_CHECKING, Any, NoReturn from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument @@ -30,10 +29,12 @@ from pymongo.errors import ClientBulkWriteException, OperationFailure from pymongo.helpers_shared import _get_wce_doc from pymongo.message import _ClientBulkWriteContext -from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + from pymongo.typings import _AgnosticMongoClient, _DocumentOut, _Pipeline + from pymongo.write_concern import WriteConcern def _merge_command( @@ -98,9 +99,9 @@ def __init__( client: _AgnosticMongoClient, write_concern: WriteConcern, ordered: bool = True, - bypass_document_validation: Optional[bool] = None, - comment: Optional[str] = None, - let: Optional[Any] = None, + bypass_document_validation: bool | None = None, + comment: str | None = None, + let: Any | None = None, verbose_results: bool = False, ) -> None: """Initialize a _AgnosticClientBulkBase instance.""" @@ -143,13 +144,13 @@ def add_update( self, namespace: str, selector: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, multi: bool, - upsert: Optional[bool] = None, - collation: Optional[Mapping[str, Any]] = None, - array_filters: Optional[list[Mapping[str, Any]]] = None, - hint: Union[str, dict[str, Any], None] = None, - sort: Optional[Mapping[str, Any]] = None, + upsert: bool | None = None, + collation: Mapping[str, Any] | None = None, + array_filters: list[Mapping[str, Any]] | None = None, + hint: str | dict[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Create an update document and add it to the list of ops.""" validate_ok_for_update(update) @@ -183,10 +184,10 @@ def add_replace( namespace: str, selector: Mapping[str, Any], replacement: Mapping[str, Any], - upsert: Optional[bool] = None, - collation: Optional[Mapping[str, Any]] = None, - hint: Union[str, dict[str, Any], None] = None, - sort: Optional[Mapping[str, Any]] = None, + upsert: bool | None = None, + collation: Mapping[str, Any] | None = None, + hint: str | dict[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Create a replace document and add it to the list of ops.""" validate_ok_for_replace(replacement) @@ -214,8 +215,8 @@ def add_delete( namespace: str, selector: Mapping[str, Any], multi: bool, - collation: Optional[Mapping[str, Any]] = None, - hint: Union[str, dict[str, Any], None] = None, + collation: Mapping[str, Any] | None = None, + hint: str | dict[str, Any] | None = None, ) -> None: """Create a delete document and add it to the list of ops.""" cmd = {"delete": -1, "filter": selector, "multi": multi} diff --git a/pymongo/_csot.py b/pymongo/_csot.py index e7c6e4e3fa..25654240ed 100644 --- a/pymongo/_csot.py +++ b/pymongo/_csot.py @@ -23,12 +23,14 @@ from collections.abc import Callable, MutableMapping from contextlib import AbstractContextManager from contextvars import ContextVar, Token -from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast +from typing import TYPE_CHECKING, Any, TypeVar, cast if TYPE_CHECKING: + from types import TracebackType + from pymongo.write_concern import WriteConcern -TIMEOUT: ContextVar[Optional[float]] = ContextVar("TIMEOUT", default=None) +TIMEOUT: ContextVar[float | None] = ContextVar("TIMEOUT", default=None) RTT: ContextVar[float] = ContextVar("RTT", default=0.0) DEADLINE: ContextVar[float] = ContextVar("DEADLINE", default=float("inf")) @@ -39,7 +41,7 @@ def reset_all() -> None: DEADLINE.set(float("inf")) -def get_timeout() -> Optional[float]: +def get_timeout() -> float | None: return TIMEOUT.get(None) @@ -55,7 +57,7 @@ def set_rtt(rtt: float) -> None: RTT.set(rtt) -def remaining() -> Optional[float]: +def remaining() -> float | None: if not get_timeout(): return None return DEADLINE.get() - time.monotonic() @@ -78,9 +80,9 @@ class _TimeoutContext(AbstractContextManager[Any]): client.db.coll.insert_one({}) """ - def __init__(self, timeout: Optional[float]): + def __init__(self, timeout: float | None): self._timeout = timeout - self._tokens: Optional[tuple[Token[Optional[float]], Token[float], Token[float]]] = None + self._tokens: tuple[Token[float | None], Token[float], Token[float]] | None = None def __enter__(self) -> None: timeout_token = TIMEOUT.set(self._timeout) @@ -90,7 +92,12 @@ def __enter__(self) -> None: rtt_token = RTT.set(0.0) self._tokens = (timeout_token, deadline_token, rtt_token) - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: if self._tokens: timeout_token, deadline_token, rtt_token = self._tokens TIMEOUT.reset(timeout_token) @@ -125,12 +132,10 @@ def csot_wrapper(self: Any, *args: Any, **kwargs: Any) -> Any: return func(self, *args, **kwargs) return func(self, *args, **kwargs) - return cast(F, csot_wrapper) + return cast("F", csot_wrapper) -def apply_write_concern( - cmd: MutableMapping[str, Any], write_concern: Optional[WriteConcern] -) -> None: +def apply_write_concern(cmd: MutableMapping[str, Any], write_concern: WriteConcern | None) -> None: """Apply the given write concern to a command.""" if not write_concern or write_concern.is_server_default: return diff --git a/pymongo/_kms_connect_shared.py b/pymongo/_kms_connect_shared.py index 634619dcdf..4620883978 100644 --- a/pymongo/_kms_connect_shared.py +++ b/pymongo/_kms_connect_shared.py @@ -32,7 +32,7 @@ import urllib.parse from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass -from typing import Any, Optional +from typing import Any from pymongo.errors import ConfigurationError @@ -94,7 +94,7 @@ def _remaining(deadline: float) -> float: """Seconds left before ``deadline``.""" left = deadline - time.monotonic() if left <= 0: - raise socket.timeout("timed out connecting through the proxy") + raise TimeoutError("timed out connecting through the proxy") return left @@ -187,8 +187,8 @@ class HTTPProxyKMSConnect: def __init__( self, proxy_url: str, - ssl_context: Optional[ssl.SSLContext] = None, - headers: Optional[Mapping[str, str]] = None, + ssl_context: ssl.SSLContext | None = None, + headers: Mapping[str, str] | None = None, ): if not isinstance(proxy_url, str): raise TypeError(f"proxy_url must be a string, not {type(proxy_url)}") @@ -226,7 +226,7 @@ def __init__( raise ConfigurationError(f"invalid proxy_url: {_redact_proxy_url(proxy_url)!r}") self.port = port if split.scheme == "https": - self.ssl_context: Optional[ssl.SSLContext] = ( + self.ssl_context: ssl.SSLContext | None = ( ssl.create_default_context() if ssl_context is None else ssl_context ) else: @@ -294,7 +294,7 @@ def _tunnel(self, sock: socket.socket, context: KMSConnectContext, deadline: flo raise OSError(f"proxy refused CONNECT to {target}: {status!r}") def _bridge( - self, proxy: socket.socket, late_sockets: Optional[list[socket.socket]] = None + self, proxy: socket.socket, late_sockets: list[socket.socket] | None = None ) -> socket.socket: """Relay a TLS proxy connection through a socketpair. @@ -368,7 +368,7 @@ def relay(src: socket.socket, dst: socket.socket) -> None: return driver_side def __call__( - self, context: KMSConnectContext, *, deadline: Optional[float] = None + self, context: KMSConnectContext, *, deadline: float | None = None ) -> socket.socket: # One deadline for all three phases; per-phase timeouts would multiply # the caller's budget. @@ -380,7 +380,7 @@ def _connect_via( self, context: KMSConnectContext, deadline: float, - late_sockets: Optional[list[socket.socket]] = None, + late_sockets: list[socket.socket] | None = None, ) -> socket.socket: # A configurable KMS host could inject CR/LF into, or split the # request line of, the CONNECT request. @@ -414,7 +414,7 @@ def _connect_proxy(self, deadline: float) -> socket.socket: # # DNS resolution is not bounded by the deadline; a slow lookup can # exceed the budget, as in the driver's own connect path. - last_error: Optional[OSError] = None + last_error: OSError | None = None for family, socktype, proto, _, sockaddr in socket.getaddrinfo( self.host, self.port, type=socket.SOCK_STREAM ): @@ -423,12 +423,12 @@ def _connect_proxy(self, deadline: float) -> socket.socket: # Propagate the timeout from _remaining rather than report a # connect error. sock.settimeout(_remaining(deadline)) - except socket.timeout: + except TimeoutError: sock.close() raise try: sock.connect(sockaddr) - except socket.timeout: + except TimeoutError: # Preserve the timeout type rather than report a generic # connect error. sock.close() @@ -476,13 +476,13 @@ async def __call__(self, context: KMSConnectContext) -> socket.socket: # type: raise exc from None # The task succeeded right at the deadline. _close_late_bridge_sockets(late_sockets, future) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None if not future.done(): # The thread runs on regardless; close its late sockets. future.add_done_callback( functools.partial(_close_late_bridge_sockets, late_sockets) ) - raise socket.timeout("timed out connecting through the proxy") from None + raise TimeoutError("timed out connecting through the proxy") from None # Sphinx documents these classes under pymongo.encryption_options, the public diff --git a/pymongo/_op_id.py b/pymongo/_op_id.py index 164ceafa62..4b966d6509 100644 --- a/pymongo/_op_id.py +++ b/pymongo/_op_id.py @@ -24,9 +24,12 @@ from contextlib import AbstractContextManager from contextvars import ContextVar -from typing import Any, Optional +from typing import TYPE_CHECKING, Any -OP_ID: ContextVar[Optional[int]] = ContextVar("OP_ID", default=None) +if TYPE_CHECKING: + from types import TracebackType + +OP_ID: ContextVar[int | None] = ContextVar("OP_ID", default=None) def reset() -> None: @@ -36,11 +39,16 @@ def reset() -> None: class _OpIdContext(AbstractContextManager[Any]): """Set OP_ID for the duration of a with block.""" - def __init__(self, op_id: Optional[int]): + def __init__(self, op_id: int | None): self._op_id = op_id def __enter__(self) -> None: self._token = OP_ID.set(self._op_id) - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: OP_ID.reset(self._token) diff --git a/pymongo/_psl.py b/pymongo/_psl.py index e0130188ff..181f4c3ed1 100644 --- a/pymongo/_psl.py +++ b/pymongo/_psl.py @@ -17,9 +17,8 @@ from __future__ import annotations from pathlib import Path -from typing import Optional -_PUBLIC_SUFFIXES: Optional[tuple[set[str], set[str], set[str]]] = None +_PUBLIC_SUFFIXES: tuple[set[str], set[str], set[str]] | None = None # Single labels that srvAllowedHostsSuffix may be set to. See the # srvAllowedHostsSuffix section of the Initial DNS Seedlist Discovery spec. diff --git a/pymongo/_telemetry.py b/pymongo/_telemetry.py index 5c83b99dc9..b18276e608 100644 --- a/pymongo/_telemetry.py +++ b/pymongo/_telemetry.py @@ -17,10 +17,8 @@ from __future__ import annotations import datetime -import queue import time -from collections.abc import MutableMapping -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from pymongo import _op_id from pymongo.logger import ( @@ -39,6 +37,9 @@ from pymongo.message import _randint if TYPE_CHECKING: + import queue + from collections.abc import MutableMapping + from bson.objectid import ObjectId from pymongo.hello import Hello from pymongo.monitoring import _EventListeners @@ -57,7 +58,7 @@ def _monotonic_duration(start: float) -> float: return max(0.0, time.monotonic() - start) -def _generate_op_id_or_none(listeners: Optional[_EventListeners]) -> Optional[int]: +def _generate_op_id_or_none(listeners: _EventListeners | None) -> int | None: """Return a random operation id if it would be consumed by APM events or logging, else None.""" return ( _randint() @@ -100,14 +101,14 @@ class _CommandTelemetry: def __init__( self, - topology_id: Optional[ObjectId], + topology_id: ObjectId | None, conn: _ConnectionTelemetryInfo, - listeners: Optional[_EventListeners], + listeners: _EventListeners | None, cmd: MutableMapping[str, Any], dbname: str, request_id: int, - op_id: Optional[int], - name: Optional[str] = None, + op_id: int | None, + name: str | None = None, ) -> None: # NOTE: the _run_command fast path in command_runner.py inline this gate for performance # They must be kept in sync with any gating changes @@ -249,9 +250,9 @@ class _CmapTelemetry: def __init__( self, - client_id: Optional[ObjectId], + client_id: ObjectId | None, address: _Address, - listeners: Optional[_EventListeners], + listeners: _EventListeners | None, publish: bool, log: bool, ) -> None: @@ -299,7 +300,7 @@ def pool_ready(self) -> None: assert self._listeners is not None self._listeners.publish_pool_ready(self._address) - def pool_cleared(self, service_id: Optional[ObjectId], interrupt_connections: bool) -> None: + def pool_cleared(self, service_id: ObjectId | None, interrupt_connections: bool) -> None: """Emit the pool cleared log entry and APM event.""" # Log before publishing to prevent potential listener preemption in tests. if self._should_log: @@ -439,7 +440,7 @@ def __init__( self, topology_id: ObjectId, address: _Address, - listeners: Optional[_EventListeners], + listeners: _EventListeners | None, ) -> None: self._topology_id = topology_id self._address = address @@ -469,7 +470,7 @@ def started(self, awaited: bool) -> None: assert self._listeners is not None self._listeners.publish_server_heartbeat_started(self._address, awaited) - def emit_started_log(self, conn_id: int, server_conn_id: Optional[int], awaited: bool) -> None: + def emit_started_log(self, conn_id: int, server_conn_id: int | None, awaited: bool) -> None: """Emit the log entry for heartbeat started (after connection checkout).""" if self._should_log: self._emit_log( @@ -484,7 +485,7 @@ def succeeded( round_trip_time: float, response: Hello[Any], conn_id: int, - server_conn_id: Optional[int], + server_conn_id: int | None, ) -> None: """Emit the SUCCEEDED log entry and APM event.""" if self._should_publish: @@ -502,7 +503,7 @@ def succeeded( reply=response.document, ) - def failed(self, error: Exception, conn_id: Optional[int], awaited: bool) -> None: + def failed(self, error: Exception, conn_id: int | None, awaited: bool) -> None: """Emit the FAILED log entry and APM event.""" should_publish = self._should_publish should_log = self._should_log @@ -533,8 +534,8 @@ class _SdamTelemetry: def __init__( self, topology_id: ObjectId, - listeners: Optional[_EventListeners], - events: Optional[queue.Queue[Any]], + listeners: _EventListeners | None, + events: queue.Queue[Any] | None, ) -> None: self._topology_id = topology_id self._listeners = listeners @@ -663,7 +664,7 @@ def __init__( topology_id: ObjectId, selector: Any, operation: str, - operation_id: Optional[int], + operation_id: int | None, topology_description: TopologyDescription, ) -> None: self._topology_id = topology_id @@ -720,10 +721,10 @@ def log_server_selection_succeeded( topology_id: ObjectId, selector: Any, operation: str, - operation_id: Optional[int], + operation_id: int | None, topology_description: TopologyDescription, server_host: str, - server_port: Optional[int], + server_port: int | None, ) -> None: """Emit the server selection SUCCEEDED log entry.""" if _is_debug_enabled(_SERVER_SELECTION_LOGGER): @@ -758,9 +759,9 @@ def log_srv_monitor_invalid_host(host: str, failure: Exception) -> None: def log_command_retry( - topology_id: Optional[ObjectId], + topology_id: ObjectId | None, command_name: str, - operation_id: Optional[int], + operation_id: int | None, attempt_number: int, is_write: bool, ) -> None: diff --git a/pymongo/_version.py b/pymongo/_version.py index caaab856b1..8cca2a6eaa 100644 --- a/pymongo/_version.py +++ b/pymongo/_version.py @@ -17,16 +17,15 @@ from __future__ import annotations import re -from typing import Union -__version__ = "4.20.0.dev0" +__version__ = "4.21.0.dev0" -def get_version_tuple(version: str) -> tuple[Union[int, str], ...]: +def get_version_tuple(version: str) -> tuple[int | str, ...]: pattern = r"(?P\d+).(?P\d+).(?P\d+)(?P.*)" match = re.match(pattern, version) if match: - parts: list[Union[int, str]] = [int(match[part]) for part in ["major", "minor", "patch"]] + parts: list[int | str] = [int(match[part]) for part in ["major", "minor", "patch"]] if match["rest"]: parts.append(match["rest"]) elif re.match(r"\d+.\d+", version): diff --git a/pymongo/asynchronous/_kms_connect.py b/pymongo/asynchronous/_kms_connect.py index ab74919beb..b8be206cc2 100644 --- a/pymongo/asynchronous/_kms_connect.py +++ b/pymongo/asynchronous/_kms_connect.py @@ -25,7 +25,7 @@ import inspect import socket import ssl -from typing import TYPE_CHECKING, Any, Optional, Union, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot from pymongo._kms_connect_shared import ( @@ -36,7 +36,6 @@ from pymongo.common import CONNECT_TIMEOUT from pymongo.errors import ConfigurationError from pymongo.helpers_shared import _get_timeout_details -from pymongo.pool_options import PoolOptions from pymongo.pool_shared import ( _async_configured_socket, _async_wrap_socket_tls, @@ -45,6 +44,7 @@ ) if TYPE_CHECKING: + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address @@ -57,9 +57,9 @@ async def _connect_kms( address: _Address, opts: PoolOptions, - kms_connect_callback: Optional[AsyncKMSConnectCallback], + kms_connect_callback: AsyncKMSConnectCallback | None, timeout: float, -) -> Union[socket.socket, _sslConn]: +) -> socket.socket | _sslConn: """Connect to a KMS host and perform the TLS handshake over the socket. Uses ``kms_connect_callback`` when one is provided, otherwise connects @@ -85,7 +85,7 @@ async def _connect_kms( ) # Any: the sync version's callback returns a plain socket. result: Any = kms_connect_callback( - KMSConnectContext(host=address[0], port=cast(int, address[1]), timeout=timeout) + KMSConnectContext(host=address[0], port=cast("int", address[1]), timeout=timeout) ) remaining = _csot.remaining() if remaining is None or _IS_SYNC: @@ -102,11 +102,11 @@ async def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/asynchronous/aggregation.py b/pymongo/asynchronous/aggregation.py index 8d21ecf46f..586aaef317 100644 --- a/pymongo/asynchronous/aggregation.py +++ b/pymongo/asynchronous/aggregation.py @@ -16,8 +16,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping, MutableMapping -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo import common from pymongo.collation import validate_collation_or_none @@ -25,6 +24,8 @@ from pymongo.read_preferences import ReadPreference, _AggWritePref if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.command_cursor import AsyncCommandCursor @@ -47,13 +48,13 @@ class _AggregationCommand: def __init__( self, - target: Union[AsyncDatabase[Any], AsyncCollection[Any]], + target: AsyncDatabase[Any] | AsyncCollection[Any], cursor_class: type[AsyncCommandCursor[Any]], pipeline: _Pipeline, options: MutableMapping[str, Any], - let: Optional[Mapping[str, Any]] = None, - user_fields: Optional[MutableMapping[str, Any]] = None, - result_processor: Optional[Callable[[Mapping[str, Any]], None]] = None, + let: Mapping[str, Any] | None = None, + user_fields: MutableMapping[str, Any] | None = None, + result_processor: Callable[[Mapping[str, Any]], None] | None = None, comment: Any = None, ) -> None: if "explain" in options: @@ -103,10 +104,10 @@ def __init__( self._collation = validate_collation_or_none(options.pop("collation", None)) self._max_await_time_ms = options.pop("maxAwaitTimeMS", None) - self._write_preference: Optional[_AggWritePref] = None + self._write_preference: _AggWritePref | None = None @property - def _aggregation_target(self) -> Union[str, int]: + def _aggregation_target(self) -> str | int: """The argument to pass to the aggregate command.""" raise NotImplementedError @@ -125,8 +126,8 @@ def _database(self) -> AsyncDatabase[Any]: raise NotImplementedError def get_read_preference( - self, session: Optional[AsyncClientSession] - ) -> Union[_AggWritePref, _ServerMode]: + self, session: AsyncClientSession | None + ) -> _AggWritePref | _ServerMode: if self._write_preference: return self._write_preference pref = self._target._read_preference_for(session) @@ -136,7 +137,7 @@ def get_read_preference( async def get_cursor( self, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, server: Server, conn: AsyncConnection, read_preference: _ServerMode, diff --git a/pymongo/asynchronous/auth.py b/pymongo/asynchronous/auth.py index 2a50ff7ce8..64008c7e2f 100644 --- a/pymongo/asynchronous/auth.py +++ b/pymongo/asynchronous/auth.py @@ -21,7 +21,6 @@ import hmac import socket from base64 import standard_b64decode, standard_b64encode -from collections.abc import Callable, Coroutine, Mapping from typing import ( TYPE_CHECKING, Any, @@ -49,6 +48,8 @@ from pymongo.saslprep import saslprep if TYPE_CHECKING: + from collections.abc import Callable, Coroutine, Mapping + from pymongo.asynchronous.pool import AsyncConnection HAVE_KERBEROS = True diff --git a/pymongo/asynchronous/auth_aws.py b/pymongo/asynchronous/auth_aws.py index 7982936948..3baab405e0 100644 --- a/pymongo/asynchronous/auth_aws.py +++ b/pymongo/asynchronous/auth_aws.py @@ -16,7 +16,6 @@ from __future__ import annotations -from collections.abc import Mapping from typing import TYPE_CHECKING, Any import bson @@ -24,6 +23,8 @@ from pymongo.errors import ConfigurationError, OperationFailure if TYPE_CHECKING: + from collections.abc import Mapping + from bson.typings import _ReadableBuffer from pymongo.asynchronous.pool import AsyncConnection from pymongo.auth_shared import MongoCredential diff --git a/pymongo/asynchronous/auth_oidc.py b/pymongo/asynchronous/auth_oidc.py index b0403d372a..f9c98847b0 100644 --- a/pymongo/asynchronous/auth_oidc.py +++ b/pymongo/asynchronous/auth_oidc.py @@ -17,11 +17,9 @@ from __future__ import annotations import asyncio -import threading import time -from collections.abc import Mapping, MutableMapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any import bson from pymongo._csot import remaining @@ -41,6 +39,9 @@ from pymongo.lock import Lock, _async_create_lock if TYPE_CHECKING: + import threading + from collections.abc import Mapping, MutableMapping + from pymongo.asynchronous.pool import AsyncConnection from pymongo.auth_shared import MongoCredential @@ -54,7 +55,7 @@ class _OIDCAuthenticator(_OIDCAuthenticatorBase): else: lock: threading.Lock = field(default_factory=_async_create_lock) # type: ignore[assignment, no-redef] - async def reauthenticate(self, conn: AsyncConnection) -> Optional[Mapping[str, Any]]: + async def reauthenticate(self, conn: AsyncConnection) -> Mapping[str, Any] | None: """Handle a reauthenticate from the server.""" # Invalidate the token for the connection. self._invalidate(conn.oidc_token_gen_id) @@ -63,7 +64,7 @@ async def reauthenticate(self, conn: AsyncConnection) -> Optional[Mapping[str, A return await self._authenticate_machine(conn) return await self._authenticate_human(conn) - async def authenticate(self, conn: AsyncConnection) -> Optional[Mapping[str, Any]]: + async def authenticate(self, conn: AsyncConnection) -> Mapping[str, Any] | None: """Handle an initial authenticate request.""" # First handle speculative auth. # If it succeeded, we are done. @@ -95,7 +96,7 @@ async def _authenticate_machine(self, conn: AsyncConnection) -> Mapping[str, Any raise return await self._sasl_start_jwt(conn) - async def _authenticate_human(self, conn: AsyncConnection) -> Optional[Mapping[str, Any]]: + async def _authenticate_human(self, conn: AsyncConnection) -> Mapping[str, Any] | None: # If we have a cached access token, try a JwtStepRequest. # authentication fails with error code 18, invalidate the access token, # and try to authenticate again. If authentication fails for any other @@ -128,9 +129,9 @@ async def _authenticate_human(self, conn: AsyncConnection) -> Optional[Mapping[s # Attempt to authenticate with a JwtStepRequest. return await self._sasl_continue_jwt(conn, start_resp) - async def _get_access_token(self) -> Optional[str]: + async def _get_access_token(self) -> str | None: properties = self.properties - cb: Union[None, OIDCCallback] + cb: OIDCCallback | None resp: OIDCCallbackResult is_human = properties.human_callback is not None @@ -180,7 +181,7 @@ async def _get_access_token(self) -> Optional[str]: else: resp = cb.fetch(context) if not isinstance(resp, OIDCCallbackResult): - raise ValueError( + raise TypeError( f"Callback result must be of type OIDCCallbackResult, not {type(resp)}" ) self.refresh_token = resp.refresh_token @@ -221,7 +222,7 @@ async def _sasl_start_jwt(self, conn: AsyncConnection) -> Mapping[str, Any]: async def _authenticate_oidc( credentials: MongoCredential, conn: AsyncConnection, reauthenticate: bool -) -> Optional[Mapping[str, Any]]: +) -> Mapping[str, Any] | None: """Authenticate using MONGODB-OIDC.""" authenticator = _get_authenticator(credentials, conn.address, _OIDCAuthenticator) if reauthenticate: diff --git a/pymongo/asynchronous/bulk.py b/pymongo/asynchronous/bulk.py index 7b9e8e78af..b30210b8cd 100644 --- a/pymongo/asynchronous/bulk.py +++ b/pymongo/asynchronous/bulk.py @@ -20,18 +20,14 @@ from __future__ import annotations import copy -from collections.abc import Iterator, Mapping, MutableMapping from itertools import islice from typing import ( TYPE_CHECKING, Any, - Optional, - Union, ) from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.command_runner import ( run_bulk_write_command, ) @@ -59,6 +55,9 @@ from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, MutableMapping + + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection @@ -101,7 +100,7 @@ async def unack_write( max_doc_size: int, docs: list[Mapping[str, Any]], client: AsyncMongoClient[Any], - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: """Send an unacknowledged batch write command.""" # Historically the STARTED log omits the documents while the published # CommandStartedEvent includes them, so log ``cmd`` but publish a copy @@ -122,7 +121,7 @@ async def unack_write( async def _execute_batch_unack( self, - bwc: Union[_BulkWriteContext, _EncryptedBulkWriteContext], + bwc: _BulkWriteContext | _EncryptedBulkWriteContext, cmd: dict[str, Any], ops: list[Mapping[str, Any]], client: AsyncMongoClient[Any], @@ -149,7 +148,7 @@ async def _execute_batch_unack( async def _execute_batch( self, - bwc: Union[_BulkWriteContext, _EncryptedBulkWriteContext], + bwc: _BulkWriteContext | _EncryptedBulkWriteContext, cmd: dict[str, Any], ops: list[Mapping[str, Any]], client: AsyncMongoClient[Any], @@ -173,12 +172,12 @@ async def _execute_command( self, generator: Iterator[Any], write_concern: WriteConcern, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, - op_id: Optional[int], + op_id: int | None, retryable: bool, full_result: MutableMapping[str, Any], - final_write_concern: Optional[WriteConcern] = None, + final_write_concern: WriteConcern | None = None, ) -> None: db_name = self.collection.database.name client = self.collection.database.client @@ -276,7 +275,7 @@ async def execute_command( self, generator: Iterator[Any], write_concern: WriteConcern, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> dict[str, Any]: """Execute using write commands.""" @@ -295,7 +294,7 @@ async def execute_command( op_id = _generate_op_id_or_none(client._event_listeners) async def retryable_bulk( - session: Optional[AsyncClientSession], conn: AsyncConnection, retryable: bool + session: AsyncClientSession | None, conn: AsyncConnection, retryable: bool ) -> None: await self._execute_command( generator, @@ -425,7 +424,7 @@ async def execute_no_results( async def execute( self, write_concern: WriteConcern, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> Any: """Execute operations.""" diff --git a/pymongo/asynchronous/change_stream.py b/pymongo/asynchronous/change_stream.py index c95c23e823..868b330802 100644 --- a/pymongo/asynchronous/change_stream.py +++ b/pymongo/asynchronous/change_stream.py @@ -16,7 +16,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING from bson import _bson_to_dict from pymongo import _csot @@ -42,6 +42,8 @@ _IS_SYNC = False if TYPE_CHECKING: + from types import TracebackType + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.database import AsyncDatabase @@ -60,15 +62,13 @@ class AsyncChangeStream(_AgnosticChangeStream[_DocumentType, "AsyncMongoClient[_ .. seealso:: The MongoDB documentation on `changeStreams `_. """ - _session: Optional[AsyncClientSession] + _session: AsyncClientSession | None async def _initialize_cursor(self) -> None: # Initialize cursor. self._cursor = await self._create_cursor() - async def _run_aggregation_cmd( - self, session: Optional[AsyncClientSession] - ) -> AsyncCommandCursor: # type: ignore[type-arg] + async def _run_aggregation_cmd(self, session: AsyncClientSession | None) -> AsyncCommandCursor: # type: ignore[type-arg] """Run the full aggregation pipeline for this AsyncChangeStream and return the corresponding AsyncCommandCursor. """ @@ -150,7 +150,7 @@ async def next(self) -> _DocumentType: __anext__ = next @_csot.apply - async def try_next(self) -> Optional[_DocumentType]: + async def try_next(self) -> _DocumentType | None: """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting @@ -248,7 +248,12 @@ async def try_next(self) -> Optional[_DocumentType]: async def __aenter__(self) -> AsyncChangeStream[_DocumentType]: return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: await self.close() diff --git a/pymongo/asynchronous/client_bulk.py b/pymongo/asynchronous/client_bulk.py index 2cd9a0105b..7b2b1833ae 100644 --- a/pymongo/asynchronous/client_bulk.py +++ b/pymongo/asynchronous/client_bulk.py @@ -20,18 +20,14 @@ from __future__ import annotations import copy -from collections.abc import Mapping, MutableMapping from itertools import islice from typing import ( TYPE_CHECKING, Any, - Optional, - Union, ) from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.command_cursor import AsyncCommandCursor from pymongo.asynchronous.command_runner import ( @@ -41,8 +37,12 @@ from pymongo.asynchronous.helpers import _handle_reauth if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection + from pymongo.write_concern import WriteConcern from pymongo._client_bulk_shared import ( _AgnosticClientBulkBase, _merge_command, @@ -70,7 +70,6 @@ InsertOneResult, UpdateResult, ) -from pymongo.write_concern import WriteConcern _IS_SYNC = False @@ -86,7 +85,7 @@ async def write_command( bwc: _ClientBulkWriteContext, cmd: MutableMapping[str, Any], request_id: int, - msg: Union[bytes, dict[str, Any]], + msg: bytes | dict[str, Any], op_docs: list[Mapping[str, Any]], ns_docs: list[Mapping[str, Any]], client: AsyncMongoClient[Any], @@ -117,7 +116,7 @@ async def unack_write( op_docs: list[Mapping[str, Any]], ns_docs: list[Mapping[str, Any]], client: AsyncMongoClient[Any], - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: """Send an unacknowledged client-level batch write command.""" # Historically the STARTED log omits the ops/nsInfo while the published # CommandStartedEvent includes them, so log ``cmd`` but publish a copy @@ -173,7 +172,7 @@ async def _process_results_cursor( full_result: MutableMapping[str, Any], result: MutableMapping[str, Any], conn: AsyncConnection, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ) -> None: """Internal helper for processing the server reply command cursor.""" if result.get("cursor"): @@ -223,12 +222,12 @@ async def _process_results_cursor( async def _execute_command( self, write_concern: WriteConcern, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, - op_id: Optional[int], + op_id: int | None, retryable: bool, full_result: MutableMapping[str, Any], - final_write_concern: Optional[WriteConcern] = None, + final_write_concern: WriteConcern | None = None, ) -> None: """Internal helper for executing batches of bulkWrite commands.""" db_name = "admin" @@ -361,7 +360,7 @@ async def _execute_command( async def execute_command( self, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> MutableMapping[str, Any]: """Execute commands with w=1 WriteConcern.""" @@ -382,7 +381,7 @@ async def execute_command( op_id = _generate_op_id_or_none(self.client._event_listeners) async def retryable_bulk( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, retryable: bool, ) -> None: @@ -473,7 +472,7 @@ async def execute_no_results( async def execute( self, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> Any: """Execute operations.""" diff --git a/pymongo/asynchronous/client_session.py b/pymongo/asynchronous/client_session.py index 531d098f5a..68180c5514 100644 --- a/pymongo/asynchronous/client_session.py +++ b/pymongo/asynchronous/client_session.py @@ -138,13 +138,11 @@ import asyncio import random import time -from collections.abc import Awaitable, Callable -from contextlib import AbstractAsyncContextManager from contextvars import ContextVar, Token from typing import ( TYPE_CHECKING, Any, - Optional, + Self, TypeVar, ) @@ -171,19 +169,21 @@ PyMongoError, WTimeoutError, ) -from pymongo.read_concern import ReadConcern -from pymongo.read_preferences import _ServerMode from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + from contextlib import AbstractAsyncContextManager from types import TracebackType from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection + from pymongo.read_concern import ReadConcern + from pymongo.read_preferences import _ServerMode _IS_SYNC = False -_SESSION: ContextVar[Optional[AsyncClientSession]] = ContextVar("SESSION", default=None) +_SESSION: ContextVar[AsyncClientSession | None] = ContextVar("SESSION", default=None) class _AsyncBoundSessionContext: @@ -191,14 +191,19 @@ class _AsyncBoundSessionContext: def __init__(self, session: AsyncClientSession, end_session: bool) -> None: self._session = session - self._session_token: Optional[Token[AsyncClientSession]] = None + self._session_token: Token[AsyncClientSession] | None = None self._end_session = end_session async def __aenter__(self) -> AsyncClientSession: self._session_token = _SESSION.set(self._session) # type: ignore[assignment] return self._session - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: if self._session_token: _SESSION.reset(self._session_token) # type: ignore[arg-type] self._session_token = None @@ -212,14 +217,14 @@ class _TransactionContext: def __init__(self, session: AsyncClientSession): self.__session = session - async def __aenter__(self) -> _TransactionContext: + async def __aenter__(self) -> Self: return self async def __aexit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: if self.__session.in_transaction: if exc_val is None: @@ -232,7 +237,7 @@ class _Transaction(_TransactionBase["AsyncConnection"]): """Internal class to hold transaction information in a AsyncClientSession.""" _conn_mgr_cls = _ConnectionManager - conn_mgr: Optional[_ConnectionManager] + conn_mgr: _ConnectionManager | None async def unpin(self) -> None: self.pinned_address = None @@ -293,19 +298,24 @@ async def _end_session(self, lock: bool) -> None: self._client._return_server_session(self._server_session) self._server_session = None - async def __aenter__(self) -> AsyncClientSession: + async def __aenter__(self) -> Self: return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: await self._end_session(lock=True) async def with_transaction( self, callback: Callable[[AsyncClientSession], Awaitable[_T]], - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, - max_commit_time_ms: Optional[int] = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, + max_commit_time_ms: int | None = None, ) -> _T: """Execute a callback in a transaction. @@ -401,7 +411,7 @@ async def callback(session, custom_arg, custom_kwarg=None): """ start_time = time.monotonic() retry = 0 - last_error: Optional[BaseException] = None + last_error: BaseException | None = None while True: if retry: # Implement exponential backoff on retry. jitter = random.random() # noqa: S311 @@ -459,10 +469,10 @@ async def callback(session, custom_arg, custom_kwarg=None): async def start_transaction( self, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, - max_commit_time_ms: Optional[int] = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, + max_commit_time_ms: int | None = None, ) -> AbstractAsyncContextManager[Any]: """Start a multi-statement transaction. @@ -575,7 +585,7 @@ async def _finish_transaction_with_retry(self, command_name: str) -> dict[str, A """ async def func( - _session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable: bool + _session: AsyncClientSession | None, conn: AsyncConnection, _retryable: bool ) -> dict[str, Any]: return await self._finish_transaction(conn, command_name) diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index 55c5d98f09..3a8b7f83b8 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -18,23 +18,12 @@ import warnings from collections import abc -from collections.abc import ( - Callable, - Coroutine, - Iterable, - Iterator, - Mapping, - MutableMapping, - Sequence, -) from typing import ( TYPE_CHECKING, Any, Generic, NoReturn, - Optional, TypeVar, - Union, cast, overload, ) @@ -43,7 +32,6 @@ from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument from bson.son import SON -from bson.timestamp import Timestamp from pymongo import ASCENDING, _csot, common, helpers_shared, message from pymongo.asynchronous.aggregation import ( _CollectionAggregationCommand, @@ -101,14 +89,14 @@ _FIND_AND_MODIFY_DOC_FIELDS = {"value": 1} -_WriteOp = Union[ - InsertOne[_DocumentType], - DeleteOne, - DeleteMany, - ReplaceOne[_DocumentType], - UpdateOne, - UpdateMany, -] +_WriteOp = ( + InsertOne[_DocumentType] + | DeleteOne + | DeleteMany + | ReplaceOne[_DocumentType] + | UpdateOne + | UpdateMany +) class ReturnDocument: @@ -126,7 +114,18 @@ class ReturnDocument: if TYPE_CHECKING: + from collections.abc import ( + Callable, + Coroutine, + Iterable, + Iterator, + Mapping, + MutableMapping, + Sequence, + ) + import bson + from bson.timestamp import Timestamp from pymongo.asynchronous.aggregation import _AggregationCommand from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.database import AsyncDatabase @@ -143,12 +142,12 @@ def __init__( self, database: AsyncDatabase[_DocumentType], name: str, - create: Optional[bool] = False, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, - session: Optional[AsyncClientSession] = None, + create: bool | None = False, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> None: """Get / create an asynchronous Mongo collection. @@ -296,12 +295,12 @@ def __getitem__(self, name: str) -> AsyncCollection[_DocumentType]: def __repr__(self) -> str: return f"{type(self).__name__}({self._database!r}, {self._name!r})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, AsyncCollection): return self._database == other.database and self._name == other.name return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -338,26 +337,26 @@ def database(self) -> AsyncDatabase[_DocumentType]: def with_options( self, codec_options: None = None, - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> AsyncCollection[_DocumentType]: ... @overload def with_options( self, codec_options: bson.CodecOptions[_DocumentTypeArg], - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> AsyncCollection[_DocumentTypeArg]: ... def with_options( self, - codec_options: Optional[bson.CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: bson.CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> AsyncCollection[_DocumentType] | AsyncCollection[_DocumentTypeArg]: """Get a clone of this collection changing the specified settings. @@ -422,18 +421,18 @@ def __call__(self, *args: Any, **kwargs: Any) -> NoReturn: async def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[AsyncClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: AsyncClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> AsyncCollectionChangeStream[_DocumentType]: """Watch changes on this collection. @@ -565,16 +564,16 @@ async def _command( self, conn: AsyncConnection, command: MutableMapping[str, Any], - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[CodecOptions[Mapping[str, Any]]] = None, + read_preference: _ServerMode | None = None, + codec_options: CodecOptions[Mapping[str, Any]] | None = None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - collation: Optional[_CollationIn] = None, - session: Optional[AsyncClientSession] = None, + allowable_errors: Sequence[str | int] | None = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + collation: _CollationIn | None = None, + session: AsyncClientSession | None = None, retryable_write: bool = False, - user_fields: Optional[Any] = None, + user_fields: Any | None = None, ) -> Mapping[str, Any]: """Internal command helper. @@ -623,9 +622,9 @@ async def _create_helper( self, name: str, options: MutableMapping[str, Any], - collation: Optional[_CollationIn], - session: Optional[AsyncClientSession], - encrypted_fields: Optional[Mapping[str, Any]] = None, + collation: _CollationIn | None, + session: AsyncClientSession | None, + encrypted_fields: Mapping[str, Any] | None = None, qev2_required: bool = False, ) -> None: """Sends a create command with the given options.""" @@ -639,7 +638,7 @@ async def _create_helper( cmd.update(options) async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> None: if qev2_required and conn.max_wire_version < 21: raise ConfigurationError( @@ -662,7 +661,7 @@ async def inner( async def _create( self, options: MutableMapping[str, Any], - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ) -> None: collation = validate_collation_or_none(options.pop("collation", None)) encrypted_fields = options.pop("encryptedFields", None) @@ -691,10 +690,10 @@ async def bulk_write( self, requests: Sequence[_WriteOp[_DocumentType]], ordered: bool = True, - bypass_document_validation: Optional[bool] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, - let: Optional[Mapping[str, Any]] = None, + bypass_document_validation: bool | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, + let: Mapping[str, Any] | None = None, ) -> BulkWriteResult: """Send a batch of write operations to the server. @@ -789,10 +788,10 @@ async def _insert_one( doc: Mapping[str, Any], ordered: bool, write_concern: WriteConcern, - op_id: Optional[int], - bypass_doc_val: Optional[bool], - session: Optional[AsyncClientSession], - comment: Optional[Any] = None, + op_id: int | None, + bypass_doc_val: bool | None, + session: AsyncClientSession | None, + comment: Any | None = None, ) -> Any: """Internal helper for inserting a single document.""" write_concern = write_concern or self.write_concern @@ -802,7 +801,7 @@ async def _insert_one( command["comment"] = comment async def _insert_command( - session: Optional[AsyncClientSession], conn: AsyncConnection, retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, retryable_write: bool ) -> None: if bypass_doc_val is not None: command["bypassDocumentValidation"] = bypass_doc_val @@ -829,10 +828,10 @@ async def _insert_command( async def insert_one( self, - document: Union[_DocumentType, RawBSONDocument], - bypass_document_validation: Optional[bool] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + document: _DocumentType | RawBSONDocument, + bypass_document_validation: bool | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> InsertOneResult: """Insert a single document. @@ -894,11 +893,11 @@ async def insert_one( @_csot.apply async def insert_many( self, - documents: Iterable[Union[_DocumentType, RawBSONDocument]], + documents: Iterable[_DocumentType | RawBSONDocument], ordered: bool = True, - bypass_document_validation: Optional[bool] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> InsertManyResult: """Insert an iterable of documents. @@ -970,22 +969,22 @@ async def _update( self, conn: AsyncConnection, criteria: Mapping[str, Any], - document: Union[Mapping[str, Any], _Pipeline], + document: Mapping[str, Any] | _Pipeline, upsert: bool = False, multi: bool = False, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - bypass_doc_val: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, + bypass_doc_val: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, retryable_write: bool = False, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - ) -> Optional[Mapping[str, Any]]: + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, + ) -> Mapping[str, Any] | None: """Internal update / replace helper.""" validate_boolean("upsert", upsert) collation = validate_collation_or_none(collation) @@ -1061,27 +1060,27 @@ async def _update( async def _update_retryable( self, criteria: Mapping[str, Any], - document: Union[Mapping[str, Any], _Pipeline], + document: Mapping[str, Any] | _Pipeline, operation: str, upsert: bool = False, multi: bool = False, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - bypass_doc_val: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - ) -> Optional[Mapping[str, Any]]: + bypass_doc_val: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, + ) -> Mapping[str, Any] | None: """Internal update / replace helper.""" async def _update( - session: Optional[AsyncClientSession], conn: AsyncConnection, retryable_write: bool - ) -> Optional[Mapping[str, Any]]: + session: AsyncClientSession | None, conn: AsyncConnection, retryable_write: bool + ) -> Mapping[str, Any] | None: return await self._update( conn, criteria, @@ -1114,13 +1113,13 @@ async def replace_one( filter: Mapping[str, Any], replacement: Mapping[str, Any], upsert: bool = False, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Replace a single document matching the filter. @@ -1220,16 +1219,16 @@ async def replace_one( async def update_one( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, upsert: bool = False, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Update a single document matching the filter. @@ -1339,15 +1338,15 @@ async def update_one( async def update_many( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, upsert: bool = False, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Update one or more documents that match the filter. @@ -1438,9 +1437,9 @@ async def update_many( async def drop( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, - encrypted_fields: Optional[Mapping[str, Any]] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, + encrypted_fields: Mapping[str, Any] | None = None, ) -> None: """Alias for :meth:`~pymongo.asynchronous.database.AsyncDatabase.drop_collection`. @@ -1484,15 +1483,15 @@ async def _delete( conn: AsyncConnection, criteria: Mapping[str, Any], multi: bool, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, retryable_write: bool = False, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> Mapping[str, Any]: """Internal delete helper.""" common.validate_is_mapping("filter", criteria) @@ -1535,19 +1534,19 @@ async def _delete_retryable( self, criteria: Mapping[str, Any], multi: bool, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> Mapping[str, Any]: """Internal delete helper.""" async def _delete( - session: Optional[AsyncClientSession], conn: AsyncConnection, retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, retryable_write: bool ) -> Mapping[str, Any]: return await self._delete( conn, @@ -1574,11 +1573,11 @@ async def _delete( async def delete_one( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> DeleteResult: """Delete a single document matching the filter. @@ -1639,11 +1638,11 @@ async def delete_one( async def delete_many( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> DeleteResult: """Delete one or more documents matching the filter. @@ -1702,8 +1701,8 @@ async def delete_many( ) async def find_one( - self, filter: Optional[Any] = None, *args: Any, **kwargs: Any - ) -> Optional[_DocumentType]: + self, filter: Any | None = None, *args: Any, **kwargs: Any + ) -> _DocumentType | None: """Get a single document from the database. All arguments to :meth:`find` are also valid arguments for @@ -1978,11 +1977,11 @@ def find_raw_batches(self, *args: Any, **kwargs: Any) -> AsyncRawBatchCursor[_Do async def _count_cmd( self, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, cmd: dict[str, Any], - collation: Optional[Collation], + collation: Collation | None, ) -> int: """Internal count command helper.""" res = await self._command( @@ -1999,11 +1998,11 @@ async def _count_cmd( async def _aggregate_one_result( self, conn: AsyncConnection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, cmd: dict[str, Any], - collation: Optional[_CollationIn], - session: Optional[AsyncClientSession], - ) -> Optional[Mapping[str, Any]]: + collation: _CollationIn | None, + session: AsyncClientSession | None, + ) -> Mapping[str, Any] | None: """Internal helper to run an aggregate that returns a single result.""" result = await self._command( conn, @@ -2021,7 +2020,7 @@ async def _aggregate_one_result( batch = result["cursor"]["firstBatch"] return batch[0] if batch else None - async def estimated_document_count(self, comment: Optional[Any] = None, **kwargs: Any) -> int: + async def estimated_document_count(self, comment: Any | None = None, **kwargs: Any) -> int: """Get an estimate of the number of documents in this collection using collection metadata. @@ -2054,10 +2053,10 @@ async def estimated_document_count(self, comment: Optional[Any] = None, **kwargs kwargs["comment"] = comment async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> int: cmd: dict[str, Any] = {"count": self._name} cmd.update(kwargs) @@ -2068,8 +2067,8 @@ async def _cmd( async def count_documents( self, filter: Mapping[str, Any], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> int: """Count the number of documents in this collection. @@ -2140,10 +2139,10 @@ async def count_documents( collation = validate_collation_or_none(kwargs.pop("collation", None)) async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> int: cmd: dict[str, Any] = {"aggregate": self._name, "pipeline": pipeline, "cursor": {}} cmd.update(kwargs) @@ -2159,10 +2158,10 @@ async def _cmd( async def _retryable_non_cursor_read( self, func: Callable[ - [Optional[AsyncClientSession], Server, AsyncConnection, Optional[_ServerMode]], + [AsyncClientSession | None, Server, AsyncConnection, _ServerMode | None], Coroutine[Any, Any, T], ], - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> T: """Non-cursor read helper to handle implicit session creation.""" @@ -2173,8 +2172,8 @@ async def _retryable_non_cursor_read( async def create_indexes( self, indexes: Sequence[IndexModel], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: """Create one or more indexes on this collection. @@ -2219,7 +2218,7 @@ async def create_indexes( @_csot.apply async def _create_indexes( - self, indexes: Sequence[IndexModel], session: Optional[AsyncClientSession], **kwargs: Any + self, indexes: Sequence[IndexModel], session: AsyncClientSession | None, **kwargs: Any ) -> list[str]: """Internal createIndexes helper. @@ -2233,7 +2232,7 @@ async def _create_indexes( names = [] async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> list[str]: def gen_indexes() -> Iterator[Mapping[str, Any]]: for index in indexes: @@ -2264,8 +2263,8 @@ def gen_indexes() -> Iterator[Mapping[str, Any]]: async def create_index( self, keys: _IndexKeyHint, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> str: """Creates an index on this collection. @@ -2381,8 +2380,8 @@ async def create_index( async def drop_indexes( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Drops all indexes on this collection. @@ -2415,8 +2414,8 @@ async def drop_indexes( async def drop_index( self, index_or_name: _IndexKeyHint, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Drops the specified index on this collection. @@ -2464,8 +2463,8 @@ async def drop_index( async def _drop_index( self, index_or_name: _IndexKeyHint, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: name = index_or_name @@ -2481,7 +2480,7 @@ async def _drop_index( cmd["comment"] = comment async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> None: await self._command( conn, @@ -2496,8 +2495,8 @@ async def inner( async def list_indexes( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> AsyncCommandCursor[MutableMapping[str, Any]]: """Get a cursor over the index documents for this collection. @@ -2534,18 +2533,18 @@ async def list_indexes( async def _list_indexes( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> AsyncCommandCursor[MutableMapping[str, Any]]: codec_options: CodecOptions[Mapping[str, Any]] = CodecOptions(SON) coll = cast( - AsyncCollection[MutableMapping[str, Any]], + "AsyncCollection[MutableMapping[str, Any]]", self.with_options(codec_options=codec_options, read_preference=ReadPreference.PRIMARY), ) read_pref = (session and session._txn_read_preference()) or ReadPreference.PRIMARY async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, @@ -2581,8 +2580,8 @@ async def _cmd( async def index_information( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> MutableMapping[str, Any]: """Get information on this collection's indexes. @@ -2623,9 +2622,9 @@ async def index_information( async def list_search_indexes( self, - name: Optional[str] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + name: str | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[Mapping[str, Any]]: """Return a cursor over search indexes for the current collection. @@ -2684,8 +2683,8 @@ async def list_search_indexes( async def create_search_index( self, - model: Union[Mapping[str, Any], SearchIndexModel], - session: Optional[AsyncClientSession] = None, + model: Mapping[str, Any] | SearchIndexModel, + session: AsyncClientSession | None = None, comment: Any = None, **kwargs: Any, ) -> str: @@ -2715,8 +2714,8 @@ async def create_search_index( async def create_search_indexes( self, models: list[SearchIndexModel], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: """Create multiple search indexes for the current collection. @@ -2739,8 +2738,8 @@ async def create_search_indexes( async def _create_search_indexes( self, models: list[SearchIndexModel], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: if comment is not None: @@ -2758,7 +2757,7 @@ def gen_indexes() -> Iterator[Mapping[str, Any]]: cmd.update(kwargs) async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> list[str]: resp = await self._command( conn, @@ -2776,8 +2775,8 @@ async def inner( async def drop_search_index( self, name: str, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Delete a search index by index name. @@ -2800,7 +2799,7 @@ async def drop_search_index( cmd["comment"] = comment async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> None: await self._command( conn, @@ -2817,8 +2816,8 @@ async def update_search_index( self, name: str, definition: Mapping[str, Any], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Update a search index by replacing the existing index definition with the provided definition. @@ -2842,7 +2841,7 @@ async def update_search_index( cmd["comment"] = comment async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> None: await self._command( conn, @@ -2857,8 +2856,8 @@ async def inner( async def options( self, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, ) -> MutableMapping[str, Any]: """Get the options set on this collection. @@ -2907,9 +2906,9 @@ async def _aggregate( aggregation_command: type[_AggregationCommand], pipeline: _Pipeline, cursor_class: type[AsyncCommandCursor], # type: ignore[type-arg] - session: Optional[AsyncClientSession], - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[_DocumentType]: if comment is not None: @@ -2935,9 +2934,9 @@ async def _aggregate( async def aggregate( self, pipeline: _Pipeline, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[_DocumentType]: """Perform an aggregation using the aggregation framework on this @@ -3039,8 +3038,8 @@ async def aggregate( async def aggregate_raw_batches( self, pipeline: _Pipeline, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncRawBatchCursor[_DocumentType]: """Perform an aggregation and retrieve batches of raw BSON. @@ -3073,7 +3072,7 @@ async def aggregate_raw_batches( kwargs["comment"] = comment async with self._database.client._tmp_session(session) as s: return cast( - AsyncRawBatchCursor[_DocumentType], + "AsyncRawBatchCursor[_DocumentType]", await self._aggregate( _CollectionRawAggregationCommand, pipeline, @@ -3087,8 +3086,8 @@ async def aggregate_raw_batches( async def rename( self, new_name: str, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> MutableMapping[str, Any]: """Rename this collection. @@ -3138,7 +3137,7 @@ async def rename( client = self._database.client async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> MutableMapping[str, Any]: return await conn.command( "admin", @@ -3154,10 +3153,10 @@ async def inner( async def distinct( self, key: str, - filter: Optional[Mapping[str, Any]] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, - hint: Optional[_IndexKeyHint] = None, + filter: Mapping[str, Any] | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, + hint: _IndexKeyHint | None = None, **kwargs: Any, ) -> list[Any]: """Get a list of distinct values for `key` among all documents @@ -3213,10 +3212,10 @@ async def distinct( hint = helpers_shared._index_document(hint) async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> list: # type: ignore[type-arg] cmd = {"distinct": self._name, "key": key} cmd.update(kwargs) @@ -3241,20 +3240,20 @@ async def _cmd( async def _find_and_modify( self, filter: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]], - sort: Optional[_IndexList], - upsert: Optional[bool] = None, + projection: Mapping[str, Any] | Iterable[str] | None, + sort: _IndexList | None, + upsert: bool | None = None, return_document: bool = ReturnDocument.BEFORE, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, **kwargs: Any, ) -> Any: """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isinstance(return_document, bool): - raise ValueError( + raise TypeError( f"return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not {type(return_document)}" ) collation = validate_collation_or_none(kwargs.pop("collation", None)) @@ -3264,7 +3263,7 @@ async def _find_and_modify( write_concern = self._write_concern_for_cmd(kwargs, session) async def _find_and_modify_helper( - session: Optional[AsyncClientSession], conn: AsyncConnection, retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, retryable_write: bool ) -> Any: cmd = {"findAndModify": self._name, "query": filter, "new": return_document} if let is not None: @@ -3311,14 +3310,14 @@ async def _find_and_modify_helper( async def find_one_and_delete( self, filter: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and deletes it, returning the document. >>> await db.test.count_documents({'x': 1}) @@ -3405,16 +3404,16 @@ async def find_one_and_replace( self, filter: Mapping[str, Any], replacement: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, upsert: bool = False, return_document: bool = ReturnDocument.BEFORE, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and replaces it, returning either the original or the replaced document. @@ -3523,18 +3522,18 @@ async def find_one_and_replace( async def find_one_and_update( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, + update: Mapping[str, Any] | _Pipeline, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, upsert: bool = False, return_document: bool = ReturnDocument.BEFORE, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[AsyncClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: AsyncClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and updates it, returning either the original or the updated document. diff --git a/pymongo/asynchronous/command_cursor.py b/pymongo/asynchronous/command_cursor.py index f2e86ddcfb..370ef98af3 100644 --- a/pymongo/asynchronous/command_cursor.py +++ b/pymongo/asynchronous/command_cursor.py @@ -17,12 +17,10 @@ from __future__ import annotations from collections import deque -from collections.abc import AsyncIterator, Mapping from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, ) from bson import CodecOptions, _convert_raw_document_lists_to_streams @@ -34,6 +32,8 @@ from pymongo.typings import _Address, _DocumentType if TYPE_CHECKING: + from collections.abc import AsyncIterator, Mapping + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.pool import AsyncConnection @@ -165,7 +165,7 @@ async def next(self) -> _DocumentType: async def __anext__(self) -> _DocumentType: return await self.next() - async def _try_next(self, get_more_allowed: bool) -> Optional[_DocumentType]: + async def _try_next(self, get_more_allowed: bool) -> _DocumentType | None: """Advance the cursor blocking for at most one getMore command.""" if not len(self._data) and not self._killed and get_more_allowed: await self._refresh() @@ -174,7 +174,7 @@ async def _try_next(self, get_more_allowed: bool) -> Optional[_DocumentType]: else: return None - async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + async def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] """Get all or some available documents from the cursor.""" if not len(self._data) and not self._killed: await self._refresh() @@ -183,13 +183,14 @@ async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: result.extend(self._data) self._data.clear() else: + # A list comprehension here is slower or uses more memory. for _ in range(min(len(self._data), total)): - result.append(self._data.popleft()) + result.append(self._data.popleft()) # noqa: PERF401 return True else: return False - async def try_next(self) -> Optional[_DocumentType]: + async def try_next(self) -> _DocumentType | None: """Advance the cursor without blocking indefinitely. This method returns the next document without waiting @@ -215,10 +216,10 @@ def __init__( self, collection: AsyncCollection[_DocumentType], cursor_info: Mapping[str, Any], - address: Optional[_Address], + address: _Address | None, batch_size: int = 0, - max_await_time_ms: Optional[int] = None, - session: Optional[AsyncClientSession] = None, + max_await_time_ms: int | None = None, + session: AsyncClientSession | None = None, comment: Any = None, ) -> None: """Create a new cursor / iterator over raw batches of BSON data. @@ -243,9 +244,9 @@ def __init__( def _unpack_response( # type: ignore[override] self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions[dict[str, Any]], - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> list[Mapping[str, Any]]: raw_response = response.raw_response(cursor_id, user_fields=user_fields) diff --git a/pymongo/asynchronous/command_runner.py b/pymongo/asynchronous/command_runner.py index 63f7c8afe8..b1c5421537 100644 --- a/pymongo/asynchronous/command_runner.py +++ b/pymongo/asynchronous/command_runner.py @@ -37,12 +37,9 @@ import datetime import time -from collections.abc import Callable, Mapping, MutableMapping, Sequence from typing import ( TYPE_CHECKING, Any, - Optional, - Union, cast, ) @@ -56,6 +53,8 @@ from pymongo.monitoring import _is_speculative_authenticate if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping, Sequence + from bson import CodecOptions from bson.objectid import ObjectId from pymongo.asynchronous.client_session import AsyncClientSession @@ -79,19 +78,19 @@ async def _run_command( request_id: int, msg: bytes, *, - client: Optional[AsyncMongoClient[Any]], - session: Optional[AsyncClientSession], - listeners: Optional[_EventListeners], - topology_id: Optional[ObjectId], + client: AsyncMongoClient[Any] | None, + session: AsyncClientSession | None, + listeners: _EventListeners | None, + topology_id: ObjectId | None, codec_options: CodecOptions[_DocumentType], - user_fields: Optional[Mapping[str, Any]] = None, - orig: Optional[MutableMapping[str, Any]] = None, - op_id: Optional[int] = None, - command_name: Optional[str] = None, + user_fields: Mapping[str, Any] | None = None, + orig: MutableMapping[str, Any] | None = None, + op_id: int | None = None, + command_name: str | None = None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, parse_write_concern_error: bool = False, - pool_opts: Optional[PoolOptions] = None, + pool_opts: PoolOptions | None = None, unacknowledged: bool = False, speculative_hello: bool = False, ensure_db: bool = False, @@ -99,9 +98,9 @@ async def _run_command( max_doc_size: int = 0, more_to_come: bool = False, set_conn_more_to_come: bool = False, - unpack_res: Optional[Callable[..., Any]] = None, - cursor_id: Optional[int] = None, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], float]: + unpack_res: Callable[..., Any] | None = None, + cursor_id: int | None = None, +) -> tuple[list[dict[str, Any]], _OpMsg | None, float]: """Send ``msg`` over ``conn`` and return ``(docs, reply, duration_s)``, where ``duration_s`` is the round-trip duration in seconds. @@ -164,7 +163,7 @@ async def _run_command( # Fast path: skip telemetry construction when logging and APM are disabled # Inline enabled check here for performance - telemetry: Optional[_CommandTelemetry] = None + telemetry: _CommandTelemetry | None = None if (topology_id is not None and _is_debug_enabled(_COMMAND_LOGGER)) or ( listeners is not None and listeners.enabled_for_commands ): @@ -176,7 +175,7 @@ async def _run_command( else: start = time.monotonic() - reply: Optional[_OpMsg] = None + reply: _OpMsg | None = None docs: list[dict[str, Any]] = [{"ok": 1}] try: if more_to_come: @@ -247,11 +246,11 @@ async def run_bulk_write_command( request_id: int, msg: bytes, *, - client: Optional[AsyncMongoClient[Any]], - orig: Optional[MutableMapping[str, Any]] = None, + client: AsyncMongoClient[Any] | None, + orig: MutableMapping[str, Any] | None = None, max_doc_size: int = 0, unacknowledged: bool = False, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], float]: +) -> tuple[list[dict[str, Any]], _OpMsg | None, float]: """Send a bulk write batch and return ``(docs, reply, duration_s)``. :param bwc: Bulk write context supplying the connection, session, listeners, etc. @@ -292,18 +291,18 @@ async def run_cursor_command( request_id: int, msg: bytes, *, - client: Optional[AsyncMongoClient[Any]], - session: Optional[AsyncClientSession], - listeners: Optional[_EventListeners], + client: AsyncMongoClient[Any] | None, + session: AsyncClientSession | None, + listeners: _EventListeners | None, codec_options: CodecOptions[_DocumentType], command_name: str, - user_fields: Optional[Mapping[str, Any]] = None, - pool_opts: Optional[PoolOptions] = None, + user_fields: Mapping[str, Any] | None = None, + pool_opts: PoolOptions | None = None, max_doc_size: int = 0, more_to_come: bool = False, - unpack_res: Optional[Callable[..., Any]] = None, - cursor_id: Optional[int] = None, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], datetime.timedelta]: + unpack_res: Callable[..., Any] | None = None, + cursor_id: int | None = None, +) -> tuple[list[dict[str, Any]], _OpMsg | None, datetime.timedelta]: """Run a cursor ``find``/``getMore`` operation over ``conn``. :param conn: The AsyncConnection to send on. @@ -353,22 +352,22 @@ async def run_command( conn: AsyncConnection, dbname: str, spec: MutableMapping[str, Any], - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, codec_options: CodecOptions[_DocumentType], - session: Optional[AsyncClientSession], - client: Optional[AsyncMongoClient[Any]], + session: AsyncClientSession | None, + client: AsyncMongoClient[Any] | None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - listeners: Optional[_EventListeners] = None, - max_bson_size: Optional[int] = None, - read_concern: Optional[ReadConcern] = None, + allowable_errors: Sequence[str | int] | None = None, + listeners: _EventListeners | None = None, + max_bson_size: int | None = None, + read_concern: ReadConcern | None = None, parse_write_concern_error: bool = False, - collation: Optional[_CollationIn] = None, - compression_ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None, + collation: _CollationIn | None = None, + compression_ctx: SnappyContext | ZlibContext | ZstdContext | None = None, unacknowledged: bool = False, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, exhaust_allowed: bool = False, - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, ) -> _DocumentType: """Encode and execute a command over ``conn``, or raise socket.error. diff --git a/pymongo/asynchronous/cursor.py b/pymongo/asynchronous/cursor.py index 14b4faed2c..b0b4abfc94 100644 --- a/pymongo/asynchronous/cursor.py +++ b/pymongo/asynchronous/cursor.py @@ -17,13 +17,10 @@ from __future__ import annotations from collections import deque -from collections.abc import Mapping from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, cast, overload, ) @@ -49,6 +46,8 @@ from pymongo.typings import _DocumentOut, _DocumentType if TYPE_CHECKING: + from collections.abc import Mapping + from bson.codec_options import CodecOptions from pymongo.asynchronous.collection import AsyncCollection @@ -87,9 +86,7 @@ def __getitem__(self, index: int) -> _DocumentType: ... @overload def __getitem__(self, index: slice) -> AsyncCursor[_DocumentType]: ... - def __getitem__( - self, index: Union[int, slice] - ) -> Union[_DocumentType, AsyncCursor[_DocumentType]]: + def __getitem__(self, index: int | slice) -> _DocumentType | AsyncCursor[_DocumentType]: """Get a single document or a slice of documents from this cursor. .. warning:: A :class:`~AsyncCursor` is not a Python :class:`list`. Each @@ -221,7 +218,7 @@ async def distinct(self, key: str) -> list[Any]: return await self._collection.distinct(key, session=self._session, **options) - async def _send_message(self, operation: Union[_Query, _GetMore]) -> None: + async def _send_message(self, operation: _Query | _GetMore) -> None: """Send a query or getmore operation and handles the response. If operation is ``None`` this is an exhaust cursor, which reads @@ -389,7 +386,7 @@ async def next(self) -> _DocumentType: else: raise StopAsyncIteration - async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + async def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] """Get all or some documents from the cursor.""" if self._empty: return False @@ -398,8 +395,9 @@ async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: result.extend(self._data) self._data.clear() else: + # A list comprehension here is slower or uses more memory. for _ in range(min(len(self._data), total)): - result.append(self._data.popleft()) + result.append(self._data.popleft()) # noqa: PERF401 return True else: return False @@ -436,9 +434,9 @@ def __init__( def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions[Mapping[str, Any]], - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> list[_DocumentOut]: raw_response = response.raw_response(cursor_id, user_fields=user_fields) @@ -446,7 +444,7 @@ def _unpack_response( # OP_MSG returns firstBatch/nextBatch documents as a BSON array # Re-assemble the array of documents into a document stream _convert_raw_document_lists_to_streams(raw_response[0]) - return cast(list["_DocumentOut"], raw_response) + return cast("list[_DocumentOut]", raw_response) async def explain(self) -> _DocumentType: """Returns an explain plan record for this cursor. diff --git a/pymongo/asynchronous/cursor_base.py b/pymongo/asynchronous/cursor_base.py index 424a2bbd83..ac1410ddcb 100644 --- a/pymongo/asynchronous/cursor_base.py +++ b/pymongo/asynchronous/cursor_base.py @@ -17,8 +17,7 @@ from __future__ import annotations from abc import abstractmethod -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional, Union, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot from pymongo.asynchronous.command_runner import run_cursor_command @@ -30,6 +29,9 @@ from pymongo.typings import _DocumentOut, _DocumentType if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from types import TracebackType + from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.pool import AsyncConnection from pymongo.read_preferences import _ServerMode @@ -38,7 +40,7 @@ async def _operation_to_command( - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, conn: AsyncConnection, apply_timeout: bool, ) -> tuple[dict[str, Any], str]: @@ -55,7 +57,7 @@ class _ConnectionManager: """Used with exhaust cursors to ensure the connection is returned.""" def __init__(self, conn: AsyncConnection, more_to_come: bool): - self.conn: Optional[AsyncConnection] = conn + self.conn: AsyncConnection | None = conn self.more_to_come = more_to_come self._lock = _async_create_lock() @@ -73,24 +75,24 @@ class _AsyncCursorBase(_AgnosticCursorBase[_DocumentType]): """Asynchronous cursor base class.""" @property - def session(self) -> Optional[AsyncClientSession]: + def session(self) -> AsyncClientSession | None: """The cursor's :class:`~pymongo.asynchronous.client_session.AsyncClientSession`, or None. .. versionadded:: 3.6 """ - return cast("Optional[AsyncClientSession]", super().session) + return cast("AsyncClientSession | None", super().session) @abstractmethod - async def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + async def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] ... @abstractmethod def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: Any, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> Sequence[_DocumentOut]: ... @@ -98,7 +100,7 @@ def _unpack_response( async def _run_with_conn( self, conn: AsyncConnection, - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, read_preference: _ServerMode, ) -> Response: """Execute a cursor operation on the given connection and return a Response. @@ -187,11 +189,16 @@ async def close(self) -> None: """Explicitly close / kill this cursor.""" await self._die_lock() - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: await self.close() @_csot.apply - async def to_list(self, length: Optional[int] = None) -> list[_DocumentType]: + async def to_list(self, length: int | None = None) -> list[_DocumentType]: """Converts the contents of this cursor to a list more efficiently than ``[doc async for doc in cursor]``. To use:: diff --git a/pymongo/asynchronous/database.py b/pymongo/asynchronous/database.py index 88ca9cab5b..0a0f97c71b 100644 --- a/pymongo/asynchronous/database.py +++ b/pymongo/asynchronous/database.py @@ -16,22 +16,18 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Generic, NoReturn, - Optional, - Union, cast, overload, ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions from bson.dbref import DBRef -from bson.timestamp import Timestamp from pymongo import _csot, common from pymongo.asynchronous.aggregation import _DatabaseAggregationCommand from pymongo.asynchronous.change_stream import AsyncDatabaseChangeStream @@ -45,8 +41,11 @@ from pymongo.typings import _CollationIn, _DocumentType, _DocumentTypeArg, _Pipeline if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping, Sequence + import bson import bson.codec_options + from bson.timestamp import Timestamp from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.asynchronous.pool import AsyncConnection @@ -62,10 +61,10 @@ def __init__( self, client: AsyncMongoClient[_DocumentType], name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> None: """Get a database by client and name. @@ -149,26 +148,26 @@ def name(self) -> str: def with_options( self, codec_options: None = None, - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> AsyncDatabase[_DocumentType]: ... @overload def with_options( self, codec_options: bson.CodecOptions[_DocumentTypeArg], - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> AsyncDatabase[_DocumentTypeArg]: ... def with_options( self, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> AsyncDatabase[_DocumentType] | AsyncDatabase[_DocumentTypeArg]: """Get a clone of this database changing the specified settings. @@ -209,12 +208,12 @@ def with_options( read_concern or self.read_concern, ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, AsyncDatabase): return self._client == other.client and self._name == other.name return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -249,10 +248,10 @@ def __getitem__(self, name: str) -> AsyncCollection[_DocumentType]: def get_collection( self, name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> AsyncCollection[_DocumentType]: """Get a :class:`~pymongo.asynchronous.collection.AsyncCollection` with the given name and options. @@ -302,10 +301,10 @@ def get_collection( async def _get_encrypted_fields( self, kwargs: Mapping[str, Any], coll_name: str, ask_db: bool - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: encrypted_fields = kwargs.get("encryptedFields") if encrypted_fields: - return cast(Mapping[str, Any], deepcopy(encrypted_fields)) + return cast("Mapping[str, Any]", deepcopy(encrypted_fields)) if ( self.client.options.auto_encryption_opts and self.client.options.auto_encryption_opts._encrypted_fields_map @@ -314,7 +313,7 @@ async def _get_encrypted_fields( ) ): return cast( - Mapping[str, Any], + "Mapping[str, Any]", deepcopy( self.client.options.auto_encryption_opts._encrypted_fields_map[ f"{self.name}.{coll_name}" @@ -324,7 +323,7 @@ async def _get_encrypted_fields( if ask_db and self.client.options.auto_encryption_opts: options = await self[coll_name].options() if options.get("encryptedFields"): - return cast(Mapping[str, Any], deepcopy(options["encryptedFields"])) + return cast("Mapping[str, Any]", deepcopy(options["encryptedFields"])) return None # See PYTHON-3084. @@ -344,18 +343,18 @@ def __bool__(self) -> NoReturn: async def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[AsyncClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: AsyncClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> AsyncDatabaseChangeStream[_DocumentType]: """Watch changes on this database. @@ -477,12 +476,12 @@ async def watch( async def create_collection( self, name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, - session: Optional[AsyncClientSession] = None, - check_exists: Optional[bool] = True, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, + session: AsyncClientSession | None = None, + check_exists: bool | None = True, **kwargs: Any, ) -> AsyncCollection[_DocumentType]: """Create a new :class:`~pymongo.asynchronous.collection.AsyncCollection` in this @@ -634,7 +633,7 @@ async def create_collection( return coll async def aggregate( - self, pipeline: _Pipeline, session: Optional[AsyncClientSession] = None, **kwargs: Any + self, pipeline: _Pipeline, session: AsyncClientSession | None = None, **kwargs: Any ) -> AsyncCommandCursor[_DocumentType]: """Perform a database-level aggregation. @@ -720,15 +719,15 @@ async def aggregate( async def _command( self, conn: AsyncConnection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[dict[str, Any]] = DEFAULT_CODEC_OPTIONS, - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> dict[str, Any]: ... @@ -736,34 +735,33 @@ async def _command( async def _command( self, conn: AsyncConnection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[_CodecDocumentType] = ..., - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, **kwargs: Any, ) -> _CodecDocumentType: ... async def _command( self, conn: AsyncConnection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, - codec_options: Union[ - CodecOptions[dict[str, Any]], CodecOptions[_CodecDocumentType] - ] = DEFAULT_CODEC_OPTIONS, - write_concern: Optional[WriteConcern] = None, + codec_options: CodecOptions[dict[str, Any]] + | CodecOptions[_CodecDocumentType] = DEFAULT_CODEC_OPTIONS, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, **kwargs: Any, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: """Internal command helper.""" if isinstance(command, str): command = {command: value} @@ -786,44 +784,44 @@ async def _command( @overload async def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, codec_options: None = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> dict[str, Any]: ... @overload async def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, codec_options: CodecOptions[_CodecDocumentType] = ..., - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> _CodecDocumentType: ... @_csot.apply async def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[bson.codec_options.CodecOptions[_CodecDocumentType]] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, + codec_options: bson.codec_options.CodecOptions[_CodecDocumentType] | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: """Issue a MongoDB command. Send command `command` to the database and return the @@ -926,11 +924,11 @@ async def command( read_preference = (session and session._txn_read_preference()) or ReadPreference.PRIMARY async def inner( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: return await self._command( conn, command, @@ -950,13 +948,13 @@ async def inner( @_csot.apply async def cursor_command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[CodecOptions[_CodecDocumentType]] = None, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, - max_await_time_ms: Optional[int] = None, + read_preference: _ServerMode | None = None, + codec_options: CodecOptions[_CodecDocumentType] | None = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, + max_await_time_ms: int | None = None, **kwargs: Any, ) -> AsyncCommandCursor[_DocumentType]: """Issue a MongoDB command and parse the response as a cursor. @@ -1020,7 +1018,7 @@ async def cursor_command( ) or ReadPreference.PRIMARY async def inner( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, @@ -1057,15 +1055,15 @@ async def inner( async def _retryable_read_command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], operation: str, - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, ) -> dict[str, Any]: """Same as command but used for retryable read commands.""" read_preference = (session and session._txn_read_preference()) or ReadPreference.PRIMARY async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, @@ -1082,13 +1080,13 @@ async def _cmd( async def _list_collections( self, conn: AsyncConnection, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, read_preference: _ServerMode, **kwargs: Any, ) -> AsyncCommandCursor[MutableMapping[str, Any]]: """Internal listCollections helper.""" coll = cast( - AsyncCollection[MutableMapping[str, Any]], + "AsyncCollection[MutableMapping[str, Any]]", self.get_collection("$cmd", read_preference=read_preference), ) cmd = {"listCollections": 1, "cursor": {}} @@ -1109,9 +1107,9 @@ async def _list_collections( async def _list_collections_helper( self, - session: Optional[AsyncClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[MutableMapping[str, Any]]: """Get a cursor over the collections of this database. @@ -1140,7 +1138,7 @@ async def _list_collections_helper( kwargs["comment"] = comment async def _cmd( - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, @@ -1155,9 +1153,9 @@ async def _cmd( async def list_collections( self, - session: Optional[AsyncClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[MutableMapping[str, Any]]: """Get a cursor over the collections of this database. @@ -1192,9 +1190,9 @@ async def list_collections( async def _list_collection_names( self, - session: Optional[AsyncClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: if comment is not None: @@ -1217,16 +1215,16 @@ async def _list_collection_names( async def list_collection_names( self, - session: Optional[AsyncClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: - """Get a list of all the collection names in this database. + r"""Get a list of all the collection names in this database. For example, to list all non-system collections:: - filter = {"name": {"$regex": r"^(?!system\\.)"}} + filter = {"name": {"$regex": r"^(?!system\.)"}} db.list_collection_names(filter=filter) :param session: a @@ -1250,14 +1248,14 @@ async def list_collection_names( return await self._list_collection_names(session, filter, comment, **kwargs) async def _drop_helper( - self, name: str, session: Optional[AsyncClientSession] = None, comment: Optional[Any] = None + self, name: str, session: AsyncClientSession | None = None, comment: Any | None = None ) -> dict[str, Any]: command = {"drop": name} if comment is not None: command["comment"] = comment async def inner( - session: Optional[AsyncClientSession], conn: AsyncConnection, _retryable_write: bool + session: AsyncClientSession | None, conn: AsyncConnection, _retryable_write: bool ) -> dict[str, Any]: return await self._command( conn, @@ -1273,10 +1271,10 @@ async def inner( @_csot.apply async def drop_collection( self, - name_or_collection: Union[str, AsyncCollection[_DocumentTypeArg]], - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, - encrypted_fields: Optional[Mapping[str, Any]] = None, + name_or_collection: str | AsyncCollection[_DocumentTypeArg], + session: AsyncClientSession | None = None, + comment: Any | None = None, + encrypted_fields: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Drop a collection. @@ -1350,12 +1348,12 @@ async def drop_collection( async def validate_collection( self, - name_or_collection: Union[str, AsyncCollection[_DocumentTypeArg]], + name_or_collection: str | AsyncCollection[_DocumentTypeArg], scandata: bool = False, full: bool = False, - session: Optional[AsyncClientSession] = None, - background: Optional[bool] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + background: bool | None = None, + comment: Any | None = None, ) -> dict[str, Any]: """Validate a collection. @@ -1415,7 +1413,7 @@ async def validate_collection( raise CollectionInvalid(f"{name} invalid: {info}") # Sharded results elif "raw" in result: - for _, res in result["raw"].items(): + for res in result["raw"].values(): if "result" in res: info = res["result"] if info.find("exception") != -1 or info.find("corrupt") != -1: @@ -1435,10 +1433,10 @@ async def validate_collection( async def dereference( self, dbref: DBRef, - session: Optional[AsyncClientSession] = None, - comment: Optional[Any] = None, + session: AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Dereference a :class:`~bson.dbref.DBRef`, getting the document it points to. diff --git a/pymongo/asynchronous/encryption.py b/pymongo/asynchronous/encryption.py index e4f91294a4..113b7b6612 100644 --- a/pymongo/asynchronous/encryption.py +++ b/pymongo/asynchronous/encryption.py @@ -17,19 +17,14 @@ from __future__ import annotations import asyncio -import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref -from collections.abc import AsyncGenerator, Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Generic, - Optional, - Union, cast, ) @@ -53,10 +48,7 @@ from bson.codec_options import CodecOptions from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson from pymongo import _csot, _op_id -from pymongo._kms_connect_shared import AsyncKMSConnectCallback from pymongo.asynchronous._kms_connect import _KMS_CONNECT_TIMEOUT, _connect_kms -from pymongo.asynchronous.collection import AsyncCollection -from pymongo.asynchronous.cursor import AsyncCursor from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.daemon import _spawn_daemon @@ -64,9 +56,6 @@ AutoEncryptionOpts, RangeOpts, StringOpts, - # Re-exported for backwards compatibility: TextOpts is deprecated but must - # remain importable from this module until it is removed. - TextOpts, # noqa: F401 check_min_pymongocrypt, ) from pymongo.encryption_shared import ( @@ -93,15 +82,22 @@ _raise_connection_failure, ) from pymongo.read_concern import ReadConcern -from pymongo.results import DeleteResult from pymongo.ssl_support import BLOCKING_IO_ERRORS, get_ssl_context from pymongo.typings import _DocumentType, _DocumentTypeArg from pymongo.uri_parser_shared import _parse_kms_tls_options, parse_host from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import AsyncGenerator, Mapping, MutableMapping, Sequence + from types import TracebackType + from pymongocrypt.mongocrypt import MongoCryptKmsContext + from pymongo._kms_connect_shared import AsyncKMSConnectCallback + from pymongo.asynchronous.collection import AsyncCollection + from pymongo.asynchronous.cursor import AsyncCursor + from pymongo.results import DeleteResult + _IS_SYNC = False @@ -119,9 +115,9 @@ class _EncryptionIO(AsyncMongoCryptCallback): # type: ignore[misc] def __init__( self, - client: Optional[AsyncMongoClient[_DocumentTypeArg]], + client: AsyncMongoClient[_DocumentTypeArg] | None, key_vault_coll: AsyncCollection[_DocumentTypeArg], - mongocryptd_client: Optional[AsyncMongoClient[_DocumentTypeArg]], + mongocryptd_client: AsyncMongoClient[_DocumentTypeArg] | None, opts: AutoEncryptionOpts, ): """Internal class to perform I/O on behalf of pymongocrypt.""" @@ -131,8 +127,8 @@ def __init__( self.client_ref = weakref.ref(client) else: self.client_ref = None - self.key_vault_coll: Optional[AsyncCollection[RawBSONDocument]] = cast( - AsyncCollection[RawBSONDocument], + self.key_vault_coll: AsyncCollection[RawBSONDocument] | None = cast( + "AsyncCollection[RawBSONDocument]", key_vault_coll.with_options( codec_options=_KEY_VAULT_OPTS, read_concern=ReadConcern(level="majority"), @@ -212,7 +208,7 @@ async def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" @@ -240,7 +236,7 @@ async def kms_request(self, kms_context: MongoCryptKmsContext) -> None: ) raise exc from final_err - async def collection_info(self, database: str, filter: bytes) -> Optional[list[bytes]]: + async def collection_info(self, database: str, filter: bytes) -> list[bytes] | None: """Get the collection info for a namespace. The returned collection info is passed to libmongocrypt which reads @@ -445,7 +441,7 @@ async def encrypt( # TODO: PYTHON-1922 avoid decoding the encrypted_cmd. return _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS) - async def decrypt(self, response: bytes | memoryview) -> Optional[bytes]: + async def decrypt(self, response: bytes | memoryview) -> bytes | None: """Decrypt a MongoDB command response. :param response: A MongoDB command response as BSON. @@ -456,7 +452,7 @@ async def decrypt(self, response: bytes | memoryview) -> Optional[bytes]: with _wrap_encryption_errors(): # Don't let decryption's sub-commands inherit the in-flight op's id. with _op_id._OpIdContext(None): - return cast(bytes, await self._auto_encrypter.decrypt(response)) + return cast("bytes", await self._auto_encrypter.decrypt(response)) def _check_closed(self) -> None: if self._closed: @@ -471,47 +467,6 @@ async def close(self) -> None: self._internal_client = None -@functools.lru_cache(maxsize=1) -def _string_opts_kwarg() -> str: - """The name the installed pymongocrypt gives the string index options. - - pymongocrypt renamed ``text_opts`` to ``string_opts`` in 1.19 and accepts - only one name per release. The rename landed on master before any release - carried it, so resolve the name from the installed signature rather than - from a version comparison. Resolved lazily and cached because importing - :mod:`inspect` is too expensive to do on the import path. - """ - import inspect - - params = inspect.signature(AsyncExplicitEncrypter.encrypt).parameters - return "string_opts" if "string_opts" in params else "text_opts" - - -def _resolve_string_opts( - string_opts: Optional[StringOpts], text_opts: Optional[StringOpts] -) -> Optional[StringOpts]: - """Resolve string_opts and its former name, text_opts. - - pymongocrypt accepts only one of the two names per release, so passing the - name the installed pymongocrypt does not support is an error. - """ - if string_opts is not None and text_opts is not None: - raise ConfigurationError("Cannot set both string_opts and text_opts") - if string_opts is None and text_opts is None: - return None - if text_opts is not None and _string_opts_kwarg() == "string_opts": - raise ConfigurationError( - "text_opts is not supported by the installed pymongocrypt " - "(1.19 or later). Use string_opts instead." - ) - if string_opts is not None and _string_opts_kwarg() == "text_opts": - raise ConfigurationError( - "string_opts requires pymongocrypt 1.19 or later. Use text_opts " - "with the installed pymongocrypt, or upgrade pymongocrypt." - ) - return string_opts if string_opts is not None else text_opts - - class AsyncClientEncryption(Generic[_DocumentType]): """Explicit client-side field level encryption.""" @@ -521,9 +476,9 @@ def __init__( key_vault_namespace: str, key_vault_client: AsyncMongoClient[_DocumentTypeArg], codec_options: CodecOptions[_DocumentTypeArg], - kms_tls_options: Optional[Mapping[str, Any]] = None, - key_expiration_ms: Optional[int] = None, - kms_connect_callback: Optional[AsyncKMSConnectCallback] = None, + kms_tls_options: Mapping[str, Any] | None = None, + key_expiration_ms: int | None = None, + kms_connect_callback: AsyncKMSConnectCallback | None = None, ) -> None: """Explicit client-side field level encryption. @@ -655,9 +610,7 @@ def __init__( kms_connect_callback=kms_connect_callback, ) self._kms_ssl_contexts = _parse_kms_tls_options(opts._kms_tls_options, _IS_SYNC) - self._io_callbacks: Optional[_EncryptionIO] = _EncryptionIO( - None, key_vault_coll, None, opts - ) + self._io_callbacks: _EncryptionIO | None = _EncryptionIO(None, key_vault_coll, None, opts) self._encryption = AsyncExplicitEncrypter( self._io_callbacks, _create_mongocrypt_options( @@ -676,8 +629,8 @@ async def create_encrypted_collection( database: AsyncDatabase[_DocumentTypeArg], name: str, encrypted_fields: Mapping[str, Any], - kms_provider: Optional[str] = None, - master_key: Optional[Mapping[str, Any]] = None, + kms_provider: str | None = None, + master_key: Mapping[str, Any] | None = None, **kwargs: Any, ) -> tuple[AsyncCollection[_DocumentTypeArg], Mapping[str, Any]]: """Create a collection with encryptedFields. @@ -763,9 +716,9 @@ async def create_encrypted_collection( async def create_data_key( self, kms_provider: str, - master_key: Optional[Mapping[str, Any]] = None, - key_alt_names: Optional[Sequence[str]] = None, - key_material: Optional[bytes] = None, + master_key: Mapping[str, Any] | None = None, + key_alt_names: Sequence[str] | None = None, + key_material: bytes | None = None, ) -> Binary: """Create and insert a new data key into the key vault collection. @@ -842,7 +795,7 @@ async def create_data_key( self._check_closed() with _wrap_encryption_errors(): return cast( - Binary, + "Binary", await self._encryption.create_data_key( kms_provider, master_key=master_key, @@ -855,13 +808,13 @@ async def _encrypt_helper( self, value: Any, algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, is_expression: bool = False, - string_opts: Optional[StringOpts] = None, + string_opts: StringOpts | None = None, ) -> Any: self._check_closed() if isinstance(key_id, uuid.UUID): @@ -897,7 +850,7 @@ async def _encrypt_helper( contention_factor=contention_factor, range_opts=range_opts_bytes, is_expression=is_expression, - **({_string_opts_kwarg(): string_opts_bytes} if string_opts_bytes else {}), + string_opts=string_opts_bytes, ) return decode(encrypted_doc)["v"] @@ -905,13 +858,12 @@ async def encrypt( self, value: Any, algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, - string_opts: Optional[StringOpts] = None, - text_opts: Optional[StringOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, + string_opts: StringOpts | None = None, ) -> Binary: """Encrypt a BSON value with a given key and algorithm. @@ -934,13 +886,12 @@ async def encrypt( :class:`RangeOpts` for some valid options. :param string_opts: Index options for `prefix`, `suffix`, and `substring` queries. See :class:`StringOpts` for some valid options. - :param text_opts: **DEPRECATED** - The former name of `string_opts`, - added in pymongocrypt 1.16 and accepted only through pymongocrypt - 1.18. Passing it to pymongocrypt 1.19 or later, or passing both - names, raises :exc:`~pymongo.errors.ConfigurationError`. :return: The encrypted value, a :class:`~bson.binary.Binary` with subtype 6. + .. versionchanged:: 4.20 + Removed the `text_opts` parameter. + .. versionchanged:: 4.18 Added the `string_opts` parameter, replacing the deprecated `text_opts`. @@ -958,7 +909,7 @@ async def encrypt( Added the `query_type` and `contention_factor` parameters. """ return cast( - Binary, + "Binary", await self._encrypt_helper( value=value, algorithm=algorithm, @@ -968,7 +919,7 @@ async def encrypt( contention_factor=contention_factor, range_opts=range_opts, is_expression=False, - string_opts=_resolve_string_opts(string_opts, text_opts), + string_opts=string_opts, ), ) @@ -976,11 +927,11 @@ async def encrypt_expression( self, expression: Mapping[str, Any], algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, ) -> RawBSONDocument: """Encrypt a BSON expression with a given key and algorithm. @@ -1014,7 +965,7 @@ async def encrypt_expression( .. versionadded:: 4.4 """ return cast( - RawBSONDocument, + "RawBSONDocument", await self._encrypt_helper( value=expression, algorithm=algorithm, @@ -1044,7 +995,7 @@ async def decrypt(self, value: Binary) -> Any: decrypted_doc = await self._encryption.decrypt(doc) return decode(decrypted_doc, codec_options=self._codec_options)["v"] - async def get_key(self, id: Binary) -> Optional[RawBSONDocument]: + async def get_key(self, id: Binary) -> RawBSONDocument | None: """Get a data key by id. :param id` (Binary): The UUID of a key a which must be a @@ -1103,7 +1054,7 @@ async def add_key_alt_name(self, id: Binary, key_alt_name: str) -> Any: assert self._key_vault_coll is not None return await self._key_vault_coll.find_one_and_update({"_id": id}, update) - async def get_key_by_alt_name(self, key_alt_name: str) -> Optional[RawBSONDocument]: + async def get_key_by_alt_name(self, key_alt_name: str) -> RawBSONDocument | None: """Get a key document in the key vault collection that has the given ``key_alt_name``. :param key_alt_name: (str): The key alternate name of the key to get. @@ -1116,7 +1067,7 @@ async def get_key_by_alt_name(self, key_alt_name: str) -> Optional[RawBSONDocume assert self._key_vault_coll is not None return await self._key_vault_coll.find_one({"keyAltNames": key_alt_name}) - async def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> Optional[RawBSONDocument]: + async def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> RawBSONDocument | None: """Remove ``key_alt_name`` from the set of keyAltNames in the key document with UUID ``id``. Also removes the ``keyAltNames`` field from the key document if it would otherwise be empty. @@ -1155,8 +1106,8 @@ async def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> Optional[R async def rewrap_many_data_key( self, filter: Mapping[str, Any], - provider: Optional[str] = None, - master_key: Optional[Mapping[str, Any]] = None, + provider: str | None = None, + master_key: Mapping[str, Any] | None = None, ) -> RewrapManyDataKeyResult: """Decrypts and encrypts all matching data keys in the key vault with a possibly new `master_key` value. @@ -1212,7 +1163,12 @@ async def rewrap_many_data_key( async def __aenter__(self) -> AsyncClientEncryption[_DocumentType]: return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: await self.close() def _check_closed(self) -> None: diff --git a/pymongo/asynchronous/helpers.py b/pymongo/asynchronous/helpers.py index 26b4ade00a..8a3cc6e882 100644 --- a/pymongo/asynchronous/helpers.py +++ b/pymongo/asynchronous/helpers.py @@ -72,7 +72,7 @@ async def inner(*args: Any, **kwargs: Any) -> Any: return await func(*args, **kwargs) raise - return cast(F, inner) + return cast("F", inner) async def _getaddrinfo( diff --git a/pymongo/asynchronous/mongo_client.py b/pymongo/asynchronous/mongo_client.py index e1837c05ed..520beafa72 100644 --- a/pymongo/asynchronous/mongo_client.py +++ b/pymongo/asynchronous/mongo_client.py @@ -56,12 +56,10 @@ NoReturn, Optional, TypeVar, - Union, cast, ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, TypeRegistry -from bson.timestamp import Timestamp from pymongo import _csot, _op_id, common, helpers_shared, periodic_executor from pymongo.asynchronous import client_session, database, uri_parser from pymongo.asynchronous.change_stream import AsyncChangeStream, AsyncClusterChangeStream @@ -108,7 +106,6 @@ _Op, ) from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.results import ClientBulkWriteResult from pymongo.server_description import ServerDescription from pymongo.server_selectors import writable_server_selector from pymongo.server_type import SERVER_TYPE @@ -137,6 +134,7 @@ from types import TracebackType from bson.objectid import ObjectId + from bson.timestamp import Timestamp from pymongo.asynchronous.bulk import _AsyncBulk from pymongo.asynchronous.client_session import AsyncClientSession from pymongo.asynchronous.cursor_base import _ConnectionManager @@ -146,6 +144,7 @@ from pymongo.client_session_shared import _ServerSession from pymongo.read_concern import ReadConcern from pymongo.response import Response + from pymongo.results import ClientBulkWriteResult from pymongo.server_selectors import Selection @@ -161,14 +160,14 @@ _IS_SYNC = False -_WriteOp = Union[ - InsertOne, # type: ignore[type-arg] - DeleteOne, - DeleteMany, - ReplaceOne, # type: ignore[type-arg] - UpdateOne, - UpdateMany, -] +_WriteOp = ( + InsertOne # type: ignore[type-arg] + | DeleteOne + | DeleteMany + | ReplaceOne # type: ignore[type-arg] + | UpdateOne + | UpdateMany +) class AsyncMongoClient(common.BaseObject, Generic[_DocumentType]): @@ -181,12 +180,12 @@ class AsyncMongoClient(common.BaseObject, Generic[_DocumentType]): def __init__( self, - host: Optional[Union[str, Sequence[str]]] = None, - port: Optional[int] = None, - document_class: Optional[type[_DocumentType]] = None, - tz_aware: Optional[bool] = None, - connect: Optional[bool] = None, - type_registry: Optional[TypeRegistry] = None, + host: str | Sequence[str] | None = None, + port: int | None = None, + document_class: type[_DocumentType] | None = None, + tz_aware: bool | None = None, + connect: bool | None = None, + type_registry: TypeRegistry | None = None, **kwargs: Any, ) -> None: """Client for a MongoDB instance, a replica set, or a set of mongoses. @@ -927,7 +926,7 @@ def validator(host: str) -> bool: self._lock = _async_create_lock() self._kill_cursors_queue: list = [] # type: ignore[type-arg] - self._encrypter: Optional[_Encrypter] = None + self._encrypter: _Encrypter | None = None self._resolve_srv_info.update( { @@ -965,7 +964,7 @@ def validator(host: str) -> bool: self._opened = False self._closed = False - self._loop: Optional[asyncio.AbstractEventLoop] = None + self._loop: asyncio.AbstractEventLoop | None = None if not is_srv: self._init_background() @@ -1128,7 +1127,7 @@ async def aconnect(self) -> None: """Explicitly connect to MongoDB asynchronously instead of on the first operation.""" await self._get_topology() - def _init_background(self, old_pid: Optional[int] = None) -> None: + def _init_background(self, old_pid: int | None = None) -> None: self._topology = Topology(self._topology_settings) if _HAS_REGISTER_AT_FORK: # Add this client to the list of weakly referenced items. @@ -1165,14 +1164,13 @@ def append_metadata(self, driver_info: DriverInfo) -> None: .. versionadded:: 4.14 """ - if not isinstance(driver_info, DriverInfo): raise TypeError( f"driver_info must be an instance of DriverInfo, not {type(driver_info)}" ) self._options.pool_options._update_metadata(driver_info) - def _should_pin_cursor(self, session: Optional[AsyncClientSession]) -> Optional[bool]: + def _should_pin_cursor(self, session: AsyncClientSession | None) -> bool | None: return self._options.load_balanced and not (session and session.in_transaction) def _after_fork(self) -> None: @@ -1188,18 +1186,18 @@ def _duplicate(self, **kwargs: Any) -> AsyncMongoClient: # type: ignore[type-ar async def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[client_session.AsyncClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: client_session.AsyncClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> AsyncChangeStream[_DocumentType]: """Watch changes on this cluster. @@ -1349,7 +1347,7 @@ def topology_description(self) -> TopologyDescription: return self._topology.description @property - def _topology_id(self) -> Optional[ObjectId]: + def _topology_id(self) -> ObjectId | None: return self._topology_settings._topology_id @property @@ -1378,7 +1376,7 @@ def options(self) -> ClientOptions: """ return self._options - def eq_props(self) -> tuple[tuple[_Address, ...], Optional[str], Optional[str], str]: + def eq_props(self) -> tuple[tuple[_Address, ...], str | None, str | None, str]: return ( tuple(sorted(self._resolve_srv_info["seeds"])), self._options.replica_set_name, @@ -1386,12 +1384,12 @@ def eq_props(self) -> tuple[tuple[_Address, ...], Optional[str], Optional[str], self._resolve_srv_info["srv_service_name"], ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, self.__class__): return self.eq_props() == other.eq_props() return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -1483,8 +1481,8 @@ def __del__(self) -> None: def _close_cursor_soon( self, cursor_id: int, - address: Optional[_CursorAddress], - conn_mgr: Optional[_ConnectionManager] = None, + address: _CursorAddress | None, + conn_mgr: _ConnectionManager | None = None, ) -> None: """Request that a cursor and/or connection be cleaned up soon.""" self._kill_cursors_queue.append((address, cursor_id, conn_mgr)) @@ -1496,9 +1494,9 @@ def _start_session(self, implicit: bool, **kwargs: Any) -> AsyncClientSession: def start_session( self, - causal_consistency: Optional[bool] = None, - default_transaction_options: Optional[TransactionOptions] = None, - snapshot: Optional[bool] = False, + causal_consistency: bool | None = None, + default_transaction_options: TransactionOptions | None = None, + snapshot: bool | None = False, ) -> client_session.AsyncClientSession: """Start a logical session. @@ -1524,8 +1522,8 @@ def start_session( ) def _ensure_session( - self, session: Optional[AsyncClientSession] = None - ) -> Optional[AsyncClientSession]: + self, session: AsyncClientSession | None = None + ) -> AsyncClientSession | None: """If provided session and bound session are None, lend a temporary session.""" session = session or self._get_bound_session() if session: @@ -1540,13 +1538,13 @@ def _ensure_session( return None def _send_cluster_time( - self, command: MutableMapping[str, Any], session: Optional[AsyncClientSession] + self, command: MutableMapping[str, Any], session: AsyncClientSession | None ) -> None: topology_time = self._topology.max_cluster_time() session_time = session.cluster_time if session else None if topology_time and session_time: if topology_time["clusterTime"] > session_time["clusterTime"]: - cluster_time: Optional[ClusterTime] = topology_time + cluster_time: ClusterTime | None = topology_time else: cluster_time = session_time else: @@ -1556,11 +1554,11 @@ def _send_cluster_time( def get_default_database( self, - default: Optional[str] = None, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + default: str | None = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> database.AsyncDatabase[_DocumentType]: """Get the database named in the MongoDB connection URI. @@ -1609,18 +1607,18 @@ def get_default_database( if self._default_database_name is None and default is None: raise ConfigurationError("No default database name defined or provided.") - name = cast(str, self._default_database_name or default) + name = cast("str", self._default_database_name or default) return database.AsyncDatabase( self, name, codec_options, read_preference, write_concern, read_concern ) def get_database( self, - name: Optional[str] = None, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + name: str | None = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> database.AsyncDatabase[_DocumentType]: """Get a :class:`~pymongo.asynchronous.database.AsyncDatabase` with the given name and options. @@ -1685,7 +1683,12 @@ def _database_default_options(self, name: str) -> database.AsyncDatabase: # typ async def __aenter__(self) -> AsyncMongoClient[_DocumentType]: return self - async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: await self.close() # See PYTHON-3084. @@ -1714,7 +1717,7 @@ async def _server_property(self, attr_name: str) -> Any: return getattr(server.description, attr_name) @property - async def address(self) -> Optional[tuple[str, int]]: + async def address(self) -> tuple[str, int] | None: """(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if @@ -1741,7 +1744,7 @@ async def address(self) -> Optional[tuple[str, int]]: return await self._server_property("address") @property - async def primary(self) -> Optional[tuple[str, int]]: + async def primary(self) -> tuple[str, int] | None: """The (host, port) of the current primary of the replica set. Returns ``None`` if this client is not connected to a replica set, @@ -1886,17 +1889,17 @@ async def _get_topology(self) -> Topology: self._opened = True return self._topology - def _checkout(self, server: Server, session: Optional[AsyncClientSession]) -> _ClientCheckout: + def _checkout(self, server: Server, session: AsyncClientSession | None) -> _ClientCheckout: return _ClientCheckout(self, server, session) async def _select_server( self, server_selector: Callable[[Selection], Selection], - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: """Select a server to run an operation on this client. @@ -1939,13 +1942,13 @@ async def _select_server( raise async def _conn_for_writes( - self, session: Optional[AsyncClientSession], operation: str + self, session: AsyncClientSession | None, operation: str ) -> _ClientCheckout: server = await self._select_server(writable_server_selector, session, operation) return self._checkout(server, session) def _conn_from_server( - self, read_preference: _ServerMode, server: Server, session: Optional[AsyncClientSession] + self, read_preference: _ServerMode, server: Server, session: AsyncClientSession | None ) -> _ClientReadCheckout: assert read_preference is not None, "read_preference must not be None" return _ClientReadCheckout(self, server, session, read_preference) @@ -1953,7 +1956,7 @@ def _conn_from_server( async def _conn_for_reads( self, read_preference: _ServerMode, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, ) -> _ClientReadCheckout: assert read_preference is not None, "read_preference must not be None" @@ -1963,9 +1966,9 @@ async def _conn_for_reads( @_csot.apply async def _run_operation( self, - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, run_with_conn: Callable, # type: ignore[type-arg] - address: Optional[_Address] = None, + address: _Address | None = None, ) -> Response: """Run a _Query/_GetMore operation and return a Response. @@ -1975,27 +1978,9 @@ async def _run_operation( :param address: Optional address when sending a message to a specific server, used for getMore. """ - if operation.conn_mgr: - server = await self._select_server( - operation.read_preference, - operation.session, # type: ignore[arg-type] - operation.name, - address=address, - ) - - async with operation.conn_mgr._lock: - async with _ClientCheckout.for_existing_conn( - self, - server, - operation.session, # type: ignore[arg-type] - operation.conn_mgr.conn, - ): - return await run_with_conn( - operation.conn_mgr.conn, operation, operation.read_preference - ) async def _cmd( - _session: Optional[AsyncClientSession], + _session: AsyncClientSession | None, _server: Server, conn: AsyncConnection, read_preference: _ServerMode, @@ -2010,16 +1995,17 @@ async def _cmd( address=address, retryable=isinstance(operation, _Query), operation=operation.name, + conn_mgr=operation.conn_mgr, ) async def _retry_with_session( self, retryable: bool, func: _WriteCall[T], - session: Optional[AsyncClientSession], - bulk: Optional[Union[_AsyncBulk, _AsyncClientBulk]], + session: AsyncClientSession | None, + bulk: _AsyncBulk | _AsyncClientBulk | None, operation: str, - operation_id: Optional[int] = None, + operation_id: int | None = None, ) -> T: """Execute an operation with at most one consecutive retries @@ -2046,16 +2032,17 @@ async def _retry_with_session( async def _retry_internal( self, func: _WriteCall[T] | _ReadCall[T], - session: Optional[AsyncClientSession], - bulk: Optional[Union[_AsyncBulk, _AsyncClientBulk]], + session: AsyncClientSession | None, + bulk: _AsyncBulk | _AsyncClientBulk | None, operation: str, is_read: bool = False, - address: Optional[_Address] = None, - read_pref: Optional[_ServerMode] = None, + address: _Address | None = None, + read_pref: _ServerMode | None = None, retryable: bool = False, - operation_id: Optional[int] = None, + operation_id: int | None = None, is_run_command: bool = False, is_aggregate_write: bool = False, + conn_mgr: Any = None, ) -> T: """Internal retryable helper for all client transactions. @@ -2070,6 +2057,7 @@ async def _retry_internal( :param is_run_command: If this is a runCommand operation, defaults to False :param is_aggregate_write: If this is a aggregate operation with a write, defaults to False. :param operation_id: Stable operation id shared across retries, defaults to None + :param conn_mgr: Pinned connection manager, defaults to None :return: Output of the calling func() """ @@ -2086,19 +2074,21 @@ async def _retry_internal( operation_id=operation_id, is_run_command=is_run_command, is_aggregate_write=is_aggregate_write, + conn_mgr=conn_mgr, ).run() async def _retryable_read( self, func: _ReadCall[T], read_pref: _ServerMode, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, - address: Optional[_Address] = None, + address: _Address | None = None, retryable: bool = True, - operation_id: Optional[int] = None, + operation_id: int | None = None, is_run_command: bool = False, is_aggregate_write: bool = False, + conn_mgr: Any = None, ) -> T: """Execute an operation with consecutive retries if possible @@ -2117,8 +2107,8 @@ async def _retryable_read( :param is_run_command: If this is a runCommand operation, defaults to False. :param is_aggregate_write: If this is a aggregate operation with a write, defaults to False. :param operation_id: Stable operation id shared across retries, defaults to None + :param conn_mgr: Pinned connection manager, defaults to None """ - # Ensure that the client supports retrying on reads and there is no session in # transaction, otherwise, we will not support retry behavior for this call. retryable = bool( @@ -2137,16 +2127,17 @@ async def _retryable_read( operation_id=operation_id, is_run_command=is_run_command, is_aggregate_write=is_aggregate_write, + conn_mgr=conn_mgr, ) async def _retryable_write( self, retryable: bool, func: _WriteCall[T], - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, operation: str, - bulk: Optional[Union[_AsyncBulk, _AsyncClientBulk]] = None, - operation_id: Optional[int] = None, + bulk: _AsyncBulk | _AsyncClientBulk | None = None, + operation_id: int | None = None, ) -> T: """Execute an operation with consecutive retries if possible @@ -2168,9 +2159,9 @@ async def _retryable_write( def _cleanup_cursor_no_lock( self, cursor_id: int, - address: Optional[_CursorAddress], + address: _CursorAddress | None, conn_mgr: _ConnectionManager, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ) -> None: """Cleanup a cursor from __del__ without locking. @@ -2191,9 +2182,9 @@ def _cleanup_cursor_no_lock( async def _cleanup_cursor_lock( self, cursor_id: int, - address: Optional[_CursorAddress], + address: _CursorAddress | None, conn_mgr: _ConnectionManager, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ) -> None: """Cleanup a cursor from cursor.close() using a lock. @@ -2223,9 +2214,9 @@ async def _cleanup_cursor_lock( async def _close_cursor_now( self, cursor_id: int, - address: Optional[_CursorAddress], - session: Optional[AsyncClientSession] = None, - conn_mgr: Optional[_ConnectionManager] = None, + address: _CursorAddress | None, + session: AsyncClientSession | None = None, + conn_mgr: _ConnectionManager | None = None, ) -> None: """Send a kill cursors message with the given id. @@ -2250,9 +2241,9 @@ async def _close_cursor_now( async def _kill_cursors( self, cursor_ids: Sequence[int], - address: Optional[_CursorAddress], + address: _CursorAddress | None, topology: Topology, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ) -> None: """Send a kill cursors message with the given ids.""" if address: @@ -2271,7 +2262,7 @@ async def _kill_cursor_impl( self, cursor_ids: Sequence[int], address: _CursorAddress, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, ) -> None: namespace = address.namespace @@ -2333,9 +2324,7 @@ async def _process_periodic_tasks(self) -> None: else: _log_client_error() - def _return_server_session( - self, server_session: Union[_ServerSession, _EmptyServerSession] - ) -> None: + def _return_server_session(self, server_session: _ServerSession | _EmptyServerSession) -> None: """Internal: return a _ServerSession to the pool.""" if isinstance(server_session, _EmptyServerSession): return None @@ -2343,8 +2332,8 @@ def _return_server_session( @contextlib.asynccontextmanager async def _tmp_session( - self, session: Optional[client_session.AsyncClientSession] - ) -> AsyncGenerator[Optional[client_session.AsyncClientSession], None]: + self, session: client_session.AsyncClientSession | None + ) -> AsyncGenerator[client_session.AsyncClientSession | None, None]: """If provided session is None, lend a temporary session.""" if session is not None and not isinstance(session, client_session.AsyncClientSession): raise ValueError( @@ -2377,13 +2366,13 @@ async def _tmp_session( yield None async def _process_response( - self, reply: Mapping[str, Any], session: Optional[AsyncClientSession] + self, reply: Mapping[str, Any], session: AsyncClientSession | None ) -> None: await self._topology.receive_cluster_time(reply.get("$clusterTime")) if session is not None: session._process_response(reply) - def _get_bound_session(self) -> Optional[AsyncClientSession]: + def _get_bound_session(self) -> AsyncClientSession | None: bound_session = _SESSION.get() if bound_session: if bound_session.client is self: @@ -2396,7 +2385,7 @@ def _get_bound_session(self) -> Optional[AsyncClientSession]: return None async def server_info( - self, session: Optional[client_session.AsyncClientSession] = None + self, session: client_session.AsyncClientSession | None = None ) -> dict[str, Any]: """Get information about the MongoDB server we're connected to. @@ -2407,7 +2396,7 @@ async def server_info( Added ``session`` parameter. """ return cast( # type: ignore[redundant-cast] - dict[str, Any], + "dict[str, Any]", await self.admin.command( "buildinfo", read_preference=ReadPreference.PRIMARY, session=session ), @@ -2415,8 +2404,8 @@ async def server_info( async def _list_databases( self, - session: Optional[client_session.AsyncClientSession] = None, - comment: Optional[Any] = None, + session: client_session.AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[dict[str, Any]]: cmd = {"listDatabases": 1} @@ -2437,8 +2426,8 @@ async def _list_databases( async def list_databases( self, - session: Optional[client_session.AsyncClientSession] = None, - comment: Optional[Any] = None, + session: client_session.AsyncClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> AsyncCommandCursor[dict[str, Any]]: """Get a cursor over the databases of the connected server. @@ -2471,8 +2460,8 @@ async def list_databases( async def list_database_names( self, - session: Optional[client_session.AsyncClientSession] = None, - comment: Optional[Any] = None, + session: client_session.AsyncClientSession | None = None, + comment: Any | None = None, ) -> list[str]: """Get a list of the names of all databases on the connected server. @@ -2492,9 +2481,9 @@ async def list_database_names( @_csot.apply async def drop_database( self, - name_or_database: Union[str, database.AsyncDatabase[_DocumentTypeArg]], - session: Optional[client_session.AsyncClientSession] = None, - comment: Optional[Any] = None, + name_or_database: str | database.AsyncDatabase[_DocumentTypeArg], + session: client_session.AsyncClientSession | None = None, + comment: Any | None = None, ) -> None: """Drop a database. @@ -2544,13 +2533,13 @@ async def drop_database( async def bulk_write( self, models: Sequence[_WriteOp], - session: Optional[AsyncClientSession] = None, + session: AsyncClientSession | None = None, ordered: bool = True, verbose_results: bool = False, - bypass_document_validation: Optional[bool] = None, - comment: Optional[Any] = None, - let: Optional[Mapping[str, Any]] = None, - write_concern: Optional[WriteConcern] = None, + bypass_document_validation: bool | None = None, + comment: Any | None = None, + let: Mapping[str, Any] | None = None, + write_concern: WriteConcern | None = None, ) -> ClientBulkWriteResult: """Send a batch of write operations, potentially across multiple namespaces, to the server. @@ -2698,7 +2687,7 @@ def __init__( self, client: AsyncMongoClient, # type: ignore[type-arg] server: Server, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, ): if not isinstance(client, AsyncMongoClient): # This is for compatibility with mocked and subclassed types, such as in Motor. @@ -2715,10 +2704,10 @@ def __init__( # of the pool at the time the connection attempt was started." self.sock_generation = server.pool.gen.get_overall() self.completed_handshake = False - self.service_id: Optional[ObjectId] = None + self.service_id: ObjectId | None = None self.handled = False - self._existing_conn: Optional[AsyncConnection] = None - self._pool_checkout: Optional[_PoolCheckout] = None + self._existing_conn: AsyncConnection | None = None + self._pool_checkout: _PoolCheckout | None = None self._server = server def contribute_socket(self, conn: AsyncConnection, completed_handshake: bool = True) -> None: @@ -2729,7 +2718,7 @@ def contribute_socket(self, conn: AsyncConnection, completed_handshake: bool = T self.completed_handshake = completed_handshake async def handle( - self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException] + self, exc_type: type[BaseException] | None, exc_val: BaseException | None ) -> None: if self.handled or exc_val is None: return @@ -2806,9 +2795,9 @@ async def __aenter__(self) -> AsyncConnection: async def __aexit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: # Perform SDAM error handling while the connection is still checked out. try: @@ -2824,7 +2813,7 @@ def for_existing_conn( cls, client: AsyncMongoClient, # type: ignore[type-arg] server: Server, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, conn: AsyncConnection, ) -> _ClientCheckout: """Return a _ClientCheckout for an already-checked-out connection. @@ -2851,7 +2840,7 @@ def __init__( self, client: AsyncMongoClient, # type: ignore[type-arg] server: Server, - session: Optional[AsyncClientSession], + session: AsyncClientSession | None, read_preference: _ServerMode, ) -> None: super().__init__(client, server, session) @@ -2881,7 +2870,7 @@ class _ClientConnectionRetryable( __slots__ = () _client: AsyncMongoClient[Any] - _session: Optional[AsyncClientSession] + _session: AsyncClientSession | None async def run(self) -> T: """Runs the supplied func() and attempts a retry @@ -2952,6 +2941,11 @@ async def run(self) -> T: ) ): raise + if self._conn_mgr is not None and self._conn_mgr.more_to_come: + # A receive-only exhaust getMore has no request + # in flight to retry: the error reply ends the + # stream. + raise self._retrying = True self._last_error = exc_to_check self._attempt_number += 1 @@ -3090,19 +3084,30 @@ async def _read(self) -> T: """ self._server = await self._get_server() assert self._read_pref is not None, "Read Preference required on read calls" + if self._conn_mgr is not None: + # The cursor is pinned to a connection (e.g. load-balanced mode): + # retry on that same connection. + async with self._conn_mgr._lock: + async with _ClientCheckout.for_existing_conn( + self._client, self._server, self._session, self._conn_mgr.conn + ): + return await self._run_read_func(self._conn_mgr.conn, self._read_pref) async with self._client._conn_from_server(self._read_pref, self._server, self._session) as ( conn, read_pref, ): - if self._retrying and not self._retryable and not self._always_retryable: - self._check_last_error() - if self._retrying: - self._log_retry(is_write=False) - # One operation id across all attempts of this operation if APM/logging is enabled - if self._operation_id is None: - return await self._func(self._session, self._server, conn, read_pref) # type: ignore - with _op_id._OpIdContext(self._operation_id): - return await self._func(self._session, self._server, conn, read_pref) # type: ignore + return await self._run_read_func(conn, read_pref) + + async def _run_read_func(self, conn: AsyncConnection, read_pref: _ServerMode) -> T: + if self._retrying and not self._retryable and not self._always_retryable: + self._check_last_error() + if self._retrying: + self._log_retry(is_write=False) + # One operation id across all attempts of this operation if APM/logging is enabled + if self._operation_id is None: + return await self._func(self._session, self._server, conn, read_pref) # type: ignore + with _op_id._OpIdContext(self._operation_id): + return await self._func(self._session, self._server, conn, read_pref) # type: ignore if _HAS_REGISTER_AT_FORK: diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index 6885fa090a..a3aebb80b0 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -21,13 +21,13 @@ import threading import time import weakref -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from pymongo import common, periodic_executor from pymongo._csot import MovingMinimum from pymongo._telemetry import _HeartbeatTelemetry, _monotonic_duration, log_srv_monitor_failure from pymongo.asynchronous.srv_resolver import _SrvResolver -from pymongo.errors import NetworkTimeout, _OperationCancelled +from pymongo.errors import ConfigurationError, NetworkTimeout, _OperationCancelled from pymongo.hello import Hello from pymongo.lock import _async_create_lock from pymongo.periodic_executor import _shutdown_executors @@ -77,7 +77,7 @@ async def target() -> bool: self._executor = executor - def _on_topology_gc(dummy: Optional[Topology] = None) -> None: + def _on_topology_gc(dummy: Topology | None = None) -> None: # This prevents GC from waiting 10 seconds for hello to complete # See test_cleanup_executors_on_client_del. monitor = self_ref() @@ -142,9 +142,9 @@ def __init__( self._pool = pool self._settings = topology_settings self._listeners = self._settings._pool_options._event_listeners - self._cancel_context: Optional[_CancellationContext] = None - self._conn_id: Optional[int] = None - self._current_hb: Optional[_HeartbeatTelemetry] = None + self._cancel_context: _CancellationContext | None = None + self._conn_id: int | None = None + self._current_hb: _HeartbeatTelemetry | None = None self._awaited: bool = False self._rtt_monitor = _RttMonitor( topology, @@ -359,7 +359,7 @@ async def _run(self) -> None: # Topology was garbage-collected. await self.close() - async def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]: + async def _get_seedlist(self) -> list[tuple[str, Any]] | None: """Poll SRV records for a seedlist. Returns a list of ServerDescriptions. @@ -375,7 +375,7 @@ async def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]: seedlist, ttl = await resolver.get_hosts_and_min_ttl() if len(seedlist) == 0: # As per the spec: this should be treated as a failure. - raise Exception + raise ConfigurationError("SRV polling returned no valid hosts.") except Exception as exc: # As per the spec, upon encountering an error: # - An error must not be raised @@ -419,7 +419,7 @@ async def add_sample(self, sample: float) -> None: self._moving_average.add_sample(sample) self._moving_min.add_sample(sample) - async def get(self) -> tuple[Optional[float], float]: + async def get(self) -> tuple[float | None, float]: """Get the calculated average, or None if no samples yet and the min.""" async with self._lock: return self._moving_average.get(), self._moving_min.get() @@ -451,7 +451,7 @@ async def _ping(self) -> float: """Run a "hello" command and return the RTT.""" async with self._pool.checkout() as conn: if self._executor._stopped: - raise Exception("_RttMonitor closed") + raise Exception("_RttMonitor closed") # noqa: TRY002 start = time.monotonic() await conn.hello() return _monotonic_duration(start) diff --git a/pymongo/asynchronous/pool.py b/pymongo/asynchronous/pool.py index ee80a7b88a..e154d912a9 100644 --- a/pymongo/asynchronous/pool.py +++ b/pymongo/asynchronous/pool.py @@ -18,13 +18,10 @@ import collections import os import time -from collections.abc import Mapping, MutableMapping, Sequence from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, ) from bson import DEFAULT_CODEC_OPTIONS @@ -57,7 +54,9 @@ ConnectionClosedReason, ) from pymongo.network_layer import AsyncNetworkingInterface, async_receive_message, async_sendall -from pymongo.pool_options import PoolOptions + +# Needed for backwards-compatible imports from pool.py. +from pymongo.pool_options import PoolOptions # noqa: TC001 from pymongo.pool_shared import ( _UNDO_OPERATION_COUNT, _UNDO_PENDING, @@ -76,6 +75,7 @@ from pymongo.server_type import SERVER_TYPE if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping, Sequence from types import TracebackType from bson import CodecOptions @@ -126,8 +126,8 @@ async def hello(self) -> Hello[dict[str, Any]]: async def _hello( self, - topology_version: Optional[Any], - heartbeat_frequency: Optional[int], + topology_version: Any | None, + heartbeat_frequency: int | None, ) -> Hello[dict[str, Any]]: cmd = self.hello_cmd() performing_handshake = not self.performed_handshake @@ -179,7 +179,7 @@ async def _hello( self.supports_sessions = ( hello.logical_session_timeout_minutes is not None and hello.is_readable ) - self.logical_session_timeout_minutes: Optional[int] = hello.logical_session_timeout_minutes + self.logical_session_timeout_minutes: int | None = hello.logical_session_timeout_minutes # hello_ok is set from helloOk, which is only returned from ismaster # don't overwrite this when connection switches to hello self.hello_ok = self.hello_ok or hello.hello_ok @@ -229,16 +229,16 @@ async def command( read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[Mapping[str, Any]] = DEFAULT_CODEC_OPTIONS, # type: ignore[assignment] check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, + allowable_errors: Sequence[str | int] | None = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - collation: Optional[_CollationIn] = None, - session: Optional[AsyncClientSession] = None, - client: Optional[AsyncMongoClient[Any]] = None, + collation: _CollationIn | None = None, + session: AsyncClientSession | None = None, + client: AsyncMongoClient[Any] | None = None, retryable_write: bool = False, publish_events: bool = True, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, exhaust_allowed: bool = False, ) -> dict[str, Any]: """Execute a command or raise an error. @@ -327,7 +327,7 @@ async def send_message(self, message: bytes, max_doc_size: int) -> None: except BaseException as error: await self._raise_connection_failure(error) - async def receive_message(self, request_id: Optional[int]) -> _OpMsg: + async def receive_message(self, request_id: int | None) -> _OpMsg: """Receive a raw BSON message or raise ConnectionFailure. If any exception is raised, the socket is closed. @@ -359,7 +359,7 @@ async def authenticate(self, reauthenticate: bool = False) -> None: self.ready = True self._telemetry.connection_ready(self.id, self.creation_time) - async def close_conn(self, reason: Optional[str]) -> None: + async def close_conn(self, reason: str | None) -> None: """Close this connection with a reason.""" if self.closed: return @@ -429,7 +429,7 @@ def __init__( address: _Address, options: PoolOptions, is_sdam: bool = False, - client_id: Optional[ObjectId] = None, + client_id: ObjectId | None = None, ): """ :param address: a (hostname, port) tuple @@ -459,7 +459,7 @@ async def _reset( self, close: bool, pause: bool = True, - service_id: Optional[ObjectId] = None, + service_id: ObjectId | None = None, interrupt_connections: bool = False, ) -> None: old_state = self.state @@ -530,7 +530,7 @@ async def _reset( for conn in sockets: await conn.close_conn(ConnectionClosedReason.STALE) - async def update_is_writable(self, is_writable: Optional[bool]) -> None: + async def update_is_writable(self, is_writable: bool | None) -> None: """Updates the is_writable attribute on all sockets currently in the Pool. """ @@ -540,7 +540,7 @@ async def update_is_writable(self, is_writable: Optional[bool]) -> None: _socket.update_is_writable(self.is_writable) # type: ignore[arg-type] async def reset( - self, service_id: Optional[ObjectId] = None, interrupt_connections: bool = False + self, service_id: ObjectId | None = None, interrupt_connections: bool = False ) -> None: await self._reset( close=False, service_id=service_id, interrupt_connections=interrupt_connections @@ -621,7 +621,7 @@ async def remove_stale_sockets(self, reference_generation: int) -> None: self.requests -= 1 self.size_cond.notify() - async def connect(self, handler: Optional[_ClientCheckout] = None) -> AsyncConnection: + async def connect(self, handler: _ClientCheckout | None = None) -> AsyncConnection: """Connect to Mongo and return a new AsyncConnection. Can raise ConnectionFailure. @@ -689,7 +689,7 @@ async def connect(self, handler: Optional[_ClientCheckout] = None) -> AsyncConne return conn - def checkout(self, handler: Optional[_ClientCheckout] = None) -> _PoolCheckout: + def checkout(self, handler: _ClientCheckout | None = None) -> _PoolCheckout: """Get a connection from the pool. Always use in an async with statement:: async with pool.checkout() as connection: @@ -703,7 +703,7 @@ def checkout(self, handler: Optional[_ClientCheckout] = None) -> _PoolCheckout: return _PoolCheckout(self, handler) async def _get_conn( - self, checkout_started_time: float, handler: Optional[_ClientCheckout] = None + self, checkout_started_time: float, handler: _ClientCheckout | None = None ) -> AsyncConnection: """Get or create a AsyncConnection. Can raise ConnectionFailure.""" # We use the pid here to avoid issues with fork / multiprocessing. @@ -881,7 +881,7 @@ async def checkin(self, conn: AsyncConnection) -> None: self._pinned_sockets.discard(conn) forked = self.pid != os.getpid() # Re-apply the accounting if a BaseException interrupts here (PYTHON-6074). - close_conn_reason: Optional[str] = None + close_conn_reason: str | None = None emit_closed = False accounted = False try: @@ -967,11 +967,11 @@ class _PoolCheckout: def __init__( self, pool: Pool, - handler: Optional[_ClientCheckout] = None, + handler: _ClientCheckout | None = None, ) -> None: self._pool = pool self._handler = handler - self._conn: Optional[AsyncConnection] = None + self._conn: AsyncConnection | None = None async def __aenter__(self) -> AsyncConnection: pool = self._pool @@ -997,9 +997,9 @@ async def __aenter__(self) -> AsyncConnection: async def __aexit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: conn = self._conn if conn is None: diff --git a/pymongo/asynchronous/server.py b/pymongo/asynchronous/server.py index 8764bfcb28..32138704ec 100644 --- a/pymongo/asynchronous/server.py +++ b/pymongo/asynchronous/server.py @@ -19,7 +19,6 @@ from typing import ( TYPE_CHECKING, Any, - Optional, ) from pymongo._telemetry import _SdamTelemetry @@ -43,9 +42,9 @@ def __init__( server_description: ServerDescription, pool: Pool, monitor: Monitor, - topology_id: Optional[ObjectId] = None, - listeners: Optional[_EventListeners] = None, - events: Optional[ReferenceType[Queue[Any]]] = None, + topology_id: ObjectId | None = None, + listeners: _EventListeners | None = None, + events: ReferenceType[Queue[Any]] | None = None, ) -> None: """Represent one MongoDB server.""" self._description = server_description @@ -62,7 +61,7 @@ async def open(self) -> None: if not self._pool.opts.load_balanced: self._monitor.open() - async def reset(self, service_id: Optional[ObjectId] = None) -> None: + async def reset(self, service_id: ObjectId | None = None) -> None: """Clear the connection pool.""" await self.pool.reset(service_id) @@ -73,8 +72,12 @@ async def close(self) -> None: """ self._sdam.server_closed(self._description.address) - await self._monitor.close() - await self._pool.close() + try: + await self._monitor.close() + finally: + # The pool must close even if cancellation or an error + # interrupts the monitor close (PYTHON-6226). + await self._pool.close() def request_check(self) -> None: """Check the server's state soon.""" diff --git a/pymongo/asynchronous/settings.py b/pymongo/asynchronous/settings.py index cc397ea411..f4cae1a29d 100644 --- a/pymongo/asynchronous/settings.py +++ b/pymongo/asynchronous/settings.py @@ -18,16 +18,22 @@ import threading from collections.abc import Callable, Collection -from typing import Optional +from typing import TYPE_CHECKING -from bson.objectid import ObjectId from pymongo import common from pymongo.asynchronous import monitor, pool from pymongo.asynchronous.pool import Pool from pymongo.common import LOCAL_THRESHOLD_MS, SERVER_SELECTION_TIMEOUT -from pymongo.pool_options import PoolOptions from pymongo.settings_shared import _BaseTopologySettings -from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.pool_options import PoolOptions + from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + import threading + from collections.abc import Callable, Collection _IS_SYNC = False @@ -35,25 +41,25 @@ class TopologySettings(_BaseTopologySettings[type[Pool], type[monitor.Monitor]]): def __init__( self, - seeds: Optional[Collection[tuple[str, int]]] = None, - replica_set_name: Optional[str] = None, - pool_class: Optional[type[Pool]] = None, - pool_options: Optional[PoolOptions] = None, - monitor_class: Optional[type[monitor.Monitor]] = None, - condition_class: Optional[type[threading.Condition]] = None, + seeds: Collection[tuple[str, int]] | None = None, + replica_set_name: str | None = None, + pool_class: type[Pool] | None = None, + pool_options: PoolOptions | None = None, + monitor_class: type[monitor.Monitor] | None = None, + condition_class: type[threading.Condition] | None = None, local_threshold_ms: int = LOCAL_THRESHOLD_MS, server_selection_timeout: int = SERVER_SELECTION_TIMEOUT, heartbeat_frequency: int = common.HEARTBEAT_FREQUENCY, - server_selector: Optional[_ServerSelector] = None, - fqdn: Optional[str] = None, - direct_connection: Optional[bool] = False, - load_balanced: Optional[bool] = None, + server_selector: _ServerSelector | None = None, + fqdn: str | None = None, + direct_connection: bool | None = False, + load_balanced: bool | None = None, srv_service_name: str = common.SRV_SERVICE_NAME, srv_max_hosts: int = 0, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, server_monitoring_mode: str = common.SERVER_MONITORING_MODE, - topology_id: Optional[ObjectId] = None, + topology_id: ObjectId | None = None, ): """Represent MongoClient's configuration. diff --git a/pymongo/asynchronous/srv_resolver.py b/pymongo/asynchronous/srv_resolver.py index 18b0ad1c6f..a95f7570b0 100644 --- a/pymongo/asynchronous/srv_resolver.py +++ b/pymongo/asynchronous/srv_resolver.py @@ -18,8 +18,7 @@ import ipaddress import random -from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo._psl import SPECIAL_USE_LABELS, _to_punycode, is_public_suffix from pymongo._telemetry import log_srv_monitor_invalid_host @@ -27,6 +26,8 @@ from pymongo.errors import ConfigurationError if TYPE_CHECKING: + from collections.abc import Callable + from dns import resolver _IS_SYNC = False @@ -34,7 +35,7 @@ # dnspython can return bytes or str from various parts # of its API depending on version. We always want str. -def maybe_decode(text: Union[str, bytes]) -> str: +def maybe_decode(text: str | bytes) -> str: if isinstance(text, bytes): return text.decode() return text @@ -62,11 +63,11 @@ class _SrvResolver: def __init__( self, fqdn: str, - connect_timeout: Optional[float], + connect_timeout: float | None, srv_service_name: str, srv_max_hosts: int = 0, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ): self.__fqdn = fqdn.lower() self.__srv = srv_service_name @@ -113,7 +114,7 @@ def __init__( self.__slen = len(self.__plist) self.nparts = len(split_fqdn) - async def get_options(self) -> Optional[str]: + async def get_options(self) -> str | None: from dns import resolver try: diff --git a/pymongo/asynchronous/topology.py b/pymongo/asynchronous/topology.py index ea49537707..1471830ddf 100644 --- a/pymongo/asynchronous/topology.py +++ b/pymongo/asynchronous/topology.py @@ -18,15 +18,13 @@ import asyncio import os -import queue import random import sys import time import warnings import weakref -from collections.abc import Callable, Mapping from pathlib import Path -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot, common, helpers_shared, periodic_executor from pymongo._telemetry import ( @@ -73,6 +71,9 @@ ) if TYPE_CHECKING: + import queue + from collections.abc import Callable, Mapping + from pymongo.asynchronous.settings import TopologySettings from pymongo.typings import _Address @@ -86,7 +87,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): _settings: TopologySettings _events_executor: periodic_executor.AsyncPeriodicExecutor - _srv_monitor: Optional[SrvMonitor] + _srv_monitor: SrvMonitor | None _monitor_tasks: list[MonitorBase] def __init__(self, topology_settings: TopologySettings): @@ -162,10 +163,10 @@ async def select_servers( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - operation_id: Optional[int] = None, - deprioritized_servers: Optional[list[Server]] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + operation_id: int | None = None, + deprioritized_servers: list[Server] | None = None, ) -> list[Server]: """Return a list of Servers matching selector, or time out. @@ -202,7 +203,7 @@ async def select_servers( ) return [ - cast(Server, self.get_server_by_address(sd.address)) for sd in server_descriptions + cast("Server", self.get_server_by_address(sd.address)) for sd in server_descriptions ] async def _select_servers_loop( @@ -210,16 +211,16 @@ async def _select_servers_loop( selector: Callable[[Selection], Selection], timeout: float, operation: str, - operation_id: Optional[int], - address: Optional[_Address], - deprioritized_servers: Optional[list[Server]] = None, + operation_id: int | None, + address: _Address | None, + deprioritized_servers: list[Server] | None = None, ) -> list[ServerDescription]: """select_servers() guts. Hold the lock when calling this.""" now = time.monotonic() end_time = now + timeout logged_waiting = False # Server selection does not have APM events, gate only on logging - ss: Optional[_ServerSelectionTelemetry] = None + ss: _ServerSelectionTelemetry | None = None if _is_debug_enabled(_SERVER_SELECTION_LOGGER): ss = _ServerSelectionTelemetry( self._topology_id, selector, operation, operation_id, self.description @@ -269,10 +270,10 @@ async def _select_server( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: servers = await self.select_servers( selector, @@ -294,10 +295,10 @@ async def select_server( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: """Like select_servers, but choose a random server if several match.""" server = await self._select_server( @@ -326,8 +327,8 @@ async def select_server_by_address( self, address: _Address, operation: str, - server_selection_timeout: Optional[int] = None, - operation_id: Optional[int] = None, + server_selection_timeout: int | None = None, + operation_id: int | None = None, ) -> Server: """Return a Server for "address", reconnecting if necessary. @@ -450,7 +451,7 @@ async def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: if self._opened: await self._process_srv_update(seedlist) - async def get_primary(self) -> Optional[_Address]: + async def get_primary(self) -> _Address | None: """Return primary's address or None.""" # Implemented here in Topology instead of AsyncMongoClient, so it can lock. async with self._lock: @@ -483,7 +484,7 @@ async def get_arbiters(self) -> set[_Address]: """Return set of arbiter addresses.""" return await self._get_replica_set_members(arbiter_server_selector) - async def receive_cluster_time(self, cluster_time: Optional[Mapping[str, Any]]) -> None: + async def receive_cluster_time(self, cluster_time: Mapping[str, Any] | None) -> None: async with self._lock: self._receive_cluster_time_no_lock(cluster_time) @@ -704,10 +705,13 @@ async def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - await server.close() + # Update our state before closing: close() can cancel the + # calling task, so the stale server must be recorded as + # removed before close() runs, not after (PYTHON-6226). if not _IS_SYNC: self._monitor_tasks.append(server._monitor) self._servers.pop(address) + await server.close() async def cleanup_monitors(self) -> None: tasks = [] diff --git a/pymongo/asynchronous/uri_parser.py b/pymongo/asynchronous/uri_parser.py index a904c4d283..43c00e515a 100644 --- a/pymongo/asynchronous/uri_parser.py +++ b/pymongo/asynchronous/uri_parser.py @@ -17,8 +17,7 @@ from __future__ import annotations -from collections.abc import Callable -from typing import Any, Optional +from typing import TYPE_CHECKING, Any from pymongo.asynchronous.srv_resolver import _SrvResolver from pymongo.common import SRV_SERVICE_NAME, _CaseInsensitiveDictionary @@ -36,20 +35,23 @@ split_options, ) +if TYPE_CHECKING: + from collections.abc import Callable + _IS_SYNC = False async def parse_uri( uri: str, - default_port: Optional[int] = DEFAULT_PORT, + default_port: int | None = DEFAULT_PORT, validate: bool = True, warn: bool = False, normalize: bool = True, - connect_timeout: Optional[float] = None, - srv_service_name: Optional[str] = None, - srv_max_hosts: Optional[int] = None, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + connect_timeout: float | None = None, + srv_service_name: str | None = None, + srv_max_hosts: int | None = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ) -> dict[str, Any]: """Parse and validate a MongoDB URI. @@ -128,15 +130,15 @@ async def parse_uri( async def _parse_srv( uri: str, - default_port: Optional[int] = DEFAULT_PORT, + default_port: int | None = DEFAULT_PORT, validate: bool = True, warn: bool = False, normalize: bool = True, - connect_timeout: Optional[float] = None, - srv_service_name: Optional[str] = None, - srv_max_hosts: Optional[int] = None, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + connect_timeout: float | None = None, + srv_service_name: str | None = None, + srv_max_hosts: int | None = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ) -> dict[str, Any]: if uri.startswith(SCHEME): is_srv = False diff --git a/pymongo/auth_oidc_shared.py b/pymongo/auth_oidc_shared.py index c81bfd5e7d..fda0042c1c 100644 --- a/pymongo/auth_oidc_shared.py +++ b/pymongo/auth_oidc_shared.py @@ -19,9 +19,8 @@ import abc import os -from collections.abc import Callable, Mapping, MutableMapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from urllib.parse import quote import bson @@ -32,14 +31,16 @@ from pymongo.helpers_shared import _AUTHENTICATION_FAILURE_CODE if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping + from pymongo.auth_shared import MongoCredential @dataclass class OIDCIdPInfo: issuer: str - clientId: Optional[str] = field(default=None) - requestScopes: Optional[list[str]] = field(default=None) + clientId: str | None = field(default=None) + requestScopes: list[str] | None = field(default=None) @dataclass @@ -47,15 +48,15 @@ class OIDCCallbackContext: timeout_seconds: float username: str version: int - refresh_token: Optional[str] = field(default=None) - idp_info: Optional[OIDCIdPInfo] = field(default=None) + refresh_token: str | None = field(default=None) + idp_info: OIDCIdPInfo | None = field(default=None) @dataclass class OIDCCallbackResult: access_token: str - expires_in_seconds: Optional[float] = field(default=None) - refresh_token: Optional[str] = field(default=None) + expires_in_seconds: float | None = field(default=None) + refresh_token: str | None = field(default=None) class OIDCCallback(abc.ABC): @@ -68,11 +69,11 @@ def fetch(self, context: OIDCCallbackContext) -> OIDCCallbackResult: @dataclass class _OIDCProperties: - callback: Optional[OIDCCallback] = field(default=None) - human_callback: Optional[OIDCCallback] = field(default=None) - environment: Optional[str] = field(default=None) + callback: OIDCCallback | None = field(default=None) + human_callback: OIDCCallback | None = field(default=None) + environment: str | None = field(default=None) allowed_hosts: list[str] = field(default_factory=list) - token_resource: Optional[str] = field(default=None) + token_resource: str | None = field(default=None) username: str = "" @@ -150,13 +151,13 @@ class _OIDCAuthenticatorBase: username: str properties: _OIDCProperties - refresh_token: Optional[str] = field(default=None) - access_token: Optional[str] = field(default=None) - idp_info: Optional[OIDCIdPInfo] = field(default=None) + refresh_token: str | None = field(default=None) + access_token: str | None = field(default=None) + idp_info: OIDCIdPInfo | None = field(default=None) token_gen_id: int = field(default=0) last_call_time: float = field(default=0) - def get_spec_auth_cmd(self) -> Optional[MutableMapping[str, Any]]: + def get_spec_auth_cmd(self) -> MutableMapping[str, Any] | None: """Get the appropriate speculative auth command.""" if not self.access_token: return None @@ -167,14 +168,14 @@ def _is_auth_error(self, err: Exception) -> bool: return False return err.code == _AUTHENTICATION_FAILURE_CODE - def _invalidate(self, oidc_token_gen_id: Optional[int]) -> None: + def _invalidate(self, oidc_token_gen_id: int | None) -> None: # Ignore the invalidation if a token gen id is given and is less than our # current token gen id. if (oidc_token_gen_id or 0) < self.token_gen_id: return self.access_token = None - def _get_start_command(self, payload: Optional[Mapping[str, Any]]) -> MutableMapping[str, Any]: + def _get_start_command(self, payload: Mapping[str, Any] | None) -> MutableMapping[str, Any]: if payload is None: principal_name = self.username if principal_name: diff --git a/pymongo/auth_shared.py b/pymongo/auth_shared.py index 0cf3cd19b6..582d75e815 100644 --- a/pymongo/auth_shared.py +++ b/pymongo/auth_shared.py @@ -22,8 +22,7 @@ import typing from base64 import standard_b64encode from collections import namedtuple -from collections.abc import Callable, Mapping, MutableMapping -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from bson import Binary from pymongo.auth_oidc_shared import ( @@ -37,6 +36,8 @@ from pymongo.errors import ConfigurationError if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping + from pymongo.hello import Hello MECHANISMS = frozenset( @@ -106,11 +107,11 @@ def _validate_canonicalize_host_name(value: str | bool) -> str | bool: def _build_credentials_tuple( mech: str, - source: Optional[str], - user: Optional[str], - passwd: Optional[str], + source: str | None, + user: str | None, + passwd: str | None, extra: Mapping[str, Any], - database: Optional[str], + database: str | None, ) -> MongoCredential: """Build and return a mechanism specific credentials tuple.""" if mech not in ("MONGODB-X509", "MONGODB-AWS", "MONGODB-OIDC") and user is None: @@ -233,13 +234,13 @@ def _build_credentials_tuple( def _xor(fir: bytes, sec: bytes) -> bytes: """XOR two byte strings together.""" - return b"".join([bytes([x ^ y]) for x, y in zip(fir, sec)]) + return b"".join([bytes([x ^ y]) for x, y in zip(fir, sec, strict=True)]) def _parse_scram_response(response: bytes) -> dict[bytes, bytes]: """Split a scram response into key, value pairs.""" return dict( - typing.cast(typing.Tuple[bytes, bytes], item.split(b"=", 1)) + typing.cast("typing.Tuple[bytes, bytes]", item.split(b"=", 1)) for item in response.split(b",") ) @@ -280,19 +281,19 @@ def _password_digest(username: str, password: str) -> str: class _AuthContext: def __init__(self, credentials: MongoCredential, address: tuple[str, int]) -> None: self.credentials = credentials - self.speculative_authenticate: Optional[Mapping[str, Any]] = None + self.speculative_authenticate: Mapping[str, Any] | None = None self.address = address @staticmethod def from_credentials( creds: MongoCredential, address: tuple[str, int], spec_auth_map: Mapping[str, Any] - ) -> Optional[_AuthContext]: + ) -> _AuthContext | None: spec_cls = spec_auth_map.get(creds.mechanism) if spec_cls: - return cast(_AuthContext, spec_cls(creds, address)) + return cast("_AuthContext", spec_cls(creds, address)) return None - def speculate_command(self) -> Optional[MutableMapping[str, Any]]: + def speculate_command(self) -> MutableMapping[str, Any] | None: raise NotImplementedError def parse_response(self, hello: Hello[Mapping[str, Any]]) -> None: @@ -307,10 +308,10 @@ def __init__( self, credentials: MongoCredential, address: tuple[str, int], mechanism: str ) -> None: super().__init__(credentials, address) - self.scram_data: Optional[tuple[bytes, bytes]] = None + self.scram_data: tuple[bytes, bytes] | None = None self.mechanism = mechanism - def speculate_command(self) -> Optional[MutableMapping[str, Any]]: + def speculate_command(self) -> MutableMapping[str, Any] | None: nonce, first_bare, cmd = _authenticate_scram_start(self.credentials, self.mechanism) # The 'db' field is included only on the speculative command. cmd["db"] = self.credentials.source @@ -337,7 +338,7 @@ def __init__( super().__init__(credentials, address) self.authenticator_cls = authenticator_cls - def speculate_command(self) -> Optional[MutableMapping[str, Any]]: + def speculate_command(self) -> MutableMapping[str, Any] | None: authenticator = _get_authenticator(self.credentials, self.address, self.authenticator_cls) cmd = authenticator.get_spec_auth_cmd() if cmd is None: diff --git a/pymongo/bulk_shared.py b/pymongo/bulk_shared.py index 54f0d4cd22..0d54b73977 100644 --- a/pymongo/bulk_shared.py +++ b/pymongo/bulk_shared.py @@ -17,8 +17,7 @@ from __future__ import annotations -from collections.abc import Iterator, Mapping, MutableMapping -from typing import TYPE_CHECKING, Any, NoReturn, Optional, Union +from typing import TYPE_CHECKING, Any, NoReturn from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument @@ -38,6 +37,8 @@ ) if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, MutableMapping + from pymongo.typings import _AgnosticCollection, _DocumentOut, _DocumentType, _Pipeline @@ -149,9 +150,9 @@ def __init__( self, collection: _AgnosticCollection[_DocumentType], ordered: bool, - bypass_document_validation: Optional[bool], - comment: Optional[str] = None, - let: Optional[Any] = None, + bypass_document_validation: bool | None, + comment: str | None = None, + let: Any | None = None, ) -> None: """Initialize an _AgnosticBulkBase instance.""" self.collection = collection.with_options( @@ -162,7 +163,7 @@ def __init__( self.let = let if self.let is not None: validate_is_document_type("let", self.let) - self.comment: Optional[str] = comment + self.comment: str | None = comment self.ordered = ordered self.ops: list[tuple[int, Mapping[str, Any]]] = [] self.executed = False @@ -199,13 +200,13 @@ def add_insert(self, document: _DocumentOut) -> None: def add_update( self, selector: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, multi: bool, - upsert: Optional[bool], - collation: Optional[Mapping[str, Any]] = None, - array_filters: Optional[list[Mapping[str, Any]]] = None, - hint: Union[str, dict[str, Any], None] = None, - sort: Optional[Mapping[str, Any]] = None, + upsert: bool | None, + collation: Mapping[str, Any] | None = None, + array_filters: list[Mapping[str, Any]] | None = None, + hint: str | dict[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Create an update document and add it to the list of ops.""" validate_ok_for_update(update) @@ -232,10 +233,10 @@ def add_replace( self, selector: Mapping[str, Any], replacement: Mapping[str, Any], - upsert: Optional[bool], - collation: Optional[Mapping[str, Any]] = None, - hint: Union[str, dict[str, Any], None] = None, - sort: Optional[Mapping[str, Any]] = None, + upsert: bool | None, + collation: Mapping[str, Any] | None = None, + hint: str | dict[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Create a replace document and add it to the list of ops.""" validate_ok_for_replace(replacement) @@ -256,8 +257,8 @@ def add_delete( self, selector: Mapping[str, Any], limit: int, - collation: Optional[Mapping[str, Any]] = None, - hint: Union[str, dict[str, Any], None] = None, + collation: Mapping[str, Any] | None = None, + hint: str | dict[str, Any] | None = None, ) -> None: """Create a delete document and add it to the list of ops.""" cmd: dict[str, Any] = {"q": selector, "limit": limit} @@ -271,7 +272,7 @@ def add_delete( self.is_retryable = False self.ops.append((_DELETE, cmd)) - def gen_ordered(self) -> Iterator[Optional[_Run]]: + def gen_ordered(self) -> Iterator[_Run | None]: """Generate batches of operations, batched by type of operation, in the order **provided**. """ diff --git a/pymongo/change_stream_shared.py b/pymongo/change_stream_shared.py index 1622304cfa..427f0ac354 100644 --- a/pymongo/change_stream_shared.py +++ b/pymongo/change_stream_shared.py @@ -17,12 +17,9 @@ from __future__ import annotations import copy -from collections.abc import Mapping -from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, cast +from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast -from bson import CodecOptions from bson.raw_bson import RawBSONDocument -from bson.timestamp import Timestamp from pymongo import common from pymongo.collation import validate_collation_or_none from pymongo.errors import ( @@ -34,6 +31,10 @@ from pymongo.typings import _DocumentType if TYPE_CHECKING: + from collections.abc import Mapping + + from bson import CodecOptions + from bson.timestamp import Timestamp from pymongo.typings import ( _AgnosticClientSession, _AgnosticCollection, @@ -60,23 +61,21 @@ class _AgnosticChangeStream(Generic[_DocumentType, _ClientT]): def __init__( self, - target: Union[ - _AgnosticMongoClient, - _AgnosticDatabase[_DocumentType], - _AgnosticCollection[_DocumentType], - ], - pipeline: Optional[_Pipeline], - full_document: Optional[str], - resume_after: Optional[Mapping[str, Any]], - max_await_time_ms: Optional[int], - batch_size: Optional[int], - collation: Optional[_CollationIn], - start_at_operation_time: Optional[Timestamp], - session: Optional[_AgnosticClientSession], - start_after: Optional[Mapping[str, Any]], - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + target: _AgnosticMongoClient + | _AgnosticDatabase[_DocumentType] + | _AgnosticCollection[_DocumentType], + pipeline: _Pipeline | None, + full_document: str | None, + resume_after: Mapping[str, Any] | None, + max_await_time_ms: int | None, + batch_size: int | None, + collation: _CollationIn | None, + start_at_operation_time: Timestamp | None, + session: _AgnosticClientSession | None, + start_after: Mapping[str, Any] | None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> None: if pipeline is None: pipeline = [] @@ -187,7 +186,7 @@ def _process_result(self, result: Mapping[str, Any]) -> None: ) @property - def resume_token(self) -> Optional[Mapping[str, Any]]: + def resume_token(self) -> Mapping[str, Any] | None: """The cached resume token that will be used to resume after the most recently returned change. diff --git a/pymongo/client_options.py b/pymongo/client_options.py index b42635ef2c..aed6db0dca 100644 --- a/pymongo/client_options.py +++ b/pymongo/client_options.py @@ -19,8 +19,7 @@ from __future__ import annotations -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from bson.codec_options import _parse_codec_options from pymongo import common @@ -39,6 +38,8 @@ from pymongo.write_concern import WriteConcern, validate_boolean if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from bson.codec_options import CodecOptions from pymongo.auth_shared import MongoCredential from pymongo.encryption_options import AutoEncryptionOpts @@ -47,8 +48,8 @@ def _parse_credentials( - username: str, password: str, database: Optional[str], options: Mapping[str, Any] -) -> Optional[MongoCredential]: + username: str, password: str, database: str | None, options: Mapping[str, Any] +) -> MongoCredential | None: """Parse authentication credentials.""" mechanism = options.get("authmechanism", "DEFAULT" if username else None) source = options.get("authsource") @@ -86,9 +87,7 @@ def _parse_read_concern(options: Mapping[str, Any]) -> ReadConcern: return ReadConcern(concern) -def _parse_ssl_options( - options: Mapping[str, Any], is_sync: bool -) -> tuple[Optional[SSLContext], bool]: +def _parse_ssl_options(options: Mapping[str, Any], is_sync: bool) -> tuple[SSLContext | None, bool]: """Parse ssl options.""" use_tls = options.get("tls") if use_tls is not None: @@ -102,24 +101,27 @@ def _parse_ssl_options( allow_invalid_hostnames = options.get("tlsallowinvalidhostnames", False) disable_ocsp_endpoint_check = options.get("tlsdisableocspendpointcheck", False) - enabled_tls_opts = [] - for opt in ( - "tlscertificatekeyfile", - "tlscertificatekeyfilepassword", - "tlscafile", - "tlscrlfile", - ): - # Any non-null value of these options implies tls=True. - if options.get(opt): - enabled_tls_opts.append(opt) - for opt in ( - "tlsallowinvalidcertificates", - "tlsallowinvalidhostnames", - "tlsdisableocspendpointcheck", - ): - # A value of False for these options implies tls=True. - if opt in options and not options[opt]: - enabled_tls_opts.append(opt) + # Any non-null value of these options implies tls=True. + enabled_tls_opts = [ + opt + for opt in ( + "tlscertificatekeyfile", + "tlscertificatekeyfilepassword", + "tlscafile", + "tlscrlfile", + ) + if options.get(opt) + ] + # A value of False for these options implies tls=True. + enabled_tls_opts.extend( + opt + for opt in ( + "tlsallowinvalidcertificates", + "tlsallowinvalidhostnames", + "tlsdisableocspendpointcheck", + ) + if opt in options and not options[opt] + ) if enabled_tls_opts: if use_tls is None: @@ -151,7 +153,7 @@ def _parse_ssl_options( def _parse_pool_options( username: str, password: str, - database: Optional[str], + database: str | None, options: Mapping[str, Any], is_sync: bool, ) -> PoolOptions: @@ -166,7 +168,7 @@ def _parse_pool_options( connect_timeout = options.get("connecttimeoutms", common.CONNECT_TIMEOUT) socket_timeout = options.get("sockettimeoutms") wait_queue_timeout = options.get("waitqueuetimeoutms", common.WAIT_QUEUE_TIMEOUT) - event_listeners = cast(Optional[Sequence[_EventListener]], options.get("event_listeners")) + event_listeners = cast("Sequence[_EventListener] | None", options.get("event_listeners")) appname = options.get("appname") driver = options.get("driver") server_api = options.get("server_api") @@ -209,7 +211,7 @@ def __init__( self, username: str, password: str, - database: Optional[str], + database: str | None, options: Mapping[str, Any], is_sync: bool = True, ): @@ -255,7 +257,7 @@ def _options(self) -> Mapping[str, Any]: return self.__options @property - def connect(self) -> Optional[bool]: + def connect(self) -> bool | None: """Whether to begin discovering a MongoDB topology automatically.""" return self.__connect @@ -265,7 +267,7 @@ def codec_options(self) -> CodecOptions[Any]: return self.__codec_options @property - def direct_connection(self) -> Optional[bool]: + def direct_connection(self) -> bool | None: """Whether to connect to the deployment in 'Single' topology.""" return self.__direct_connection @@ -299,7 +301,7 @@ def read_preference(self) -> _ServerMode: return self.__read_preference @property - def replica_set_name(self) -> Optional[str]: + def replica_set_name(self) -> str | None: """Replica set name or None.""" return self.__replica_set_name @@ -314,7 +316,7 @@ def read_concern(self) -> ReadConcern: return self.__read_concern @property - def timeout(self) -> Optional[float]: + def timeout(self) -> float | None: """The configured timeoutMS converted to seconds, or None. .. versionadded:: 4.2 @@ -332,12 +334,12 @@ def retry_reads(self) -> bool: return self.__retry_reads @property - def auto_encryption_opts(self) -> Optional[AutoEncryptionOpts]: + def auto_encryption_opts(self) -> AutoEncryptionOpts | None: """A :class:`~pymongo.encryption.AutoEncryptionOpts` or None.""" return self.__auto_encryption_opts @property - def load_balanced(self) -> Optional[bool]: + def load_balanced(self) -> bool | None: """True if the client was configured to connect to a load balancer.""" return self.__load_balanced diff --git a/pymongo/client_session_shared.py b/pymongo/client_session_shared.py index 16e6794a8d..6e4ac0378f 100644 --- a/pymongo/client_session_shared.py +++ b/pymongo/client_session_shared.py @@ -25,7 +25,6 @@ Any, Generic, NoReturn, - Optional, Protocol, TypeVar, cast, @@ -86,9 +85,9 @@ class SessionOptions: def __init__( self, - causal_consistency: Optional[bool] = None, - default_transaction_options: Optional[TransactionOptions] = None, - snapshot: Optional[bool] = False, + causal_consistency: bool | None = None, + default_transaction_options: TransactionOptions | None = None, + snapshot: bool | None = False, ) -> None: if snapshot: if causal_consistency: @@ -112,7 +111,7 @@ def causal_consistency(self) -> bool: return self._causal_consistency @property - def default_transaction_options(self) -> Optional[TransactionOptions]: + def default_transaction_options(self) -> TransactionOptions | None: """The default TransactionOptions to use for transactions started on this session. @@ -121,7 +120,7 @@ def default_transaction_options(self) -> Optional[TransactionOptions]: return self._default_transaction_options @property - def snapshot(self) -> Optional[bool]: + def snapshot(self) -> bool | None: """Whether snapshot reads are configured. .. versionadded:: 3.12 @@ -159,10 +158,10 @@ class TransactionOptions: def __init__( self, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, - max_commit_time_ms: Optional[int] = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, + max_commit_time_ms: int | None = None, ) -> None: self._read_concern = read_concern self._write_concern = write_concern @@ -198,22 +197,22 @@ def __init__( ) @property - def read_concern(self) -> Optional[ReadConcern]: + def read_concern(self) -> ReadConcern | None: """This transaction's :class:`~pymongo.read_concern.ReadConcern`.""" return self._read_concern @property - def write_concern(self) -> Optional[WriteConcern]: + def write_concern(self) -> WriteConcern | None: """This transaction's :class:`~pymongo.write_concern.WriteConcern`.""" return self._write_concern @property - def read_preference(self) -> Optional[_ServerMode]: + def read_preference(self) -> _ServerMode | None: """This transaction's :class:`~pymongo.read_preferences.ReadPreference`.""" return self._read_preference @property - def max_commit_time_ms(self) -> Optional[int]: + def max_commit_time_ms(self) -> int | None: """The maxTimeMS to use when running a commitTransaction command. .. versionadded:: 3.9 @@ -222,8 +221,8 @@ def max_commit_time_ms(self) -> Optional[int]: def _validate_session_write_concern( - session: Optional[_ClientSessionT], write_concern: Optional[WriteConcern] -) -> Optional[_ClientSessionT]: + session: _ClientSessionT | None, write_concern: WriteConcern | None +) -> _ClientSessionT | None: """Validate that an explicit session is not used with an unack'ed write. Returns the session to use for the next operation. @@ -335,7 +334,7 @@ def mark_dirty(self) -> None: """ self.dirty = True - def timed_out(self, session_timeout_minutes: Optional[int]) -> bool: + def timed_out(self, session_timeout_minutes: int | None) -> bool: if session_timeout_minutes is None: return False @@ -376,7 +375,7 @@ def pop_all(self) -> list[_ServerSession]: break return ids - def get_server_session(self, session_timeout_minutes: Optional[int]) -> _ServerSession: + def get_server_session(self, session_timeout_minutes: int | None) -> _ServerSession: # Although the Driver Sessions Spec says we only clear stale sessions # in return_server_session, PyMongo can't take a lock when returning # sessions from a __del__ method (like in Cursor.__die), so it can't @@ -401,7 +400,7 @@ def return_server_session(self, server_session: _ServerSession) -> None: if server_session.generation == self.generation and not server_session.dirty: self.appendleft(server_session) - def _clear_stale(self, session_timeout_minutes: Optional[int]) -> None: + def _clear_stale(self, session_timeout_minutes: int | None) -> None: # Clear stale sessions. The least recently used are on the right. while True: try: @@ -440,8 +439,8 @@ def __init__( self._client: _ClientT = client self._server_session = server_session self._options = options - self._cluster_time: Optional[Mapping[str, Any]] = None - self._operation_time: Optional[Timestamp] = None + self._cluster_time: Mapping[str, Any] | None = None + self._operation_time: Timestamp | None = None self._snapshot_time = None # Is this an implicitly created session? self._implicit = implicit @@ -514,14 +513,14 @@ def _transaction_id(self) -> Int64: return self._server_session.transaction_id @property - def cluster_time(self) -> Optional[ClusterTime]: + def cluster_time(self) -> ClusterTime | None: """The cluster time returned by the last operation executed in this session. """ return self._cluster_time @property - def operation_time(self) -> Optional[Timestamp]: + def operation_time(self) -> Timestamp | None: """The operation time returned by the last operation executed in this session. """ @@ -537,7 +536,7 @@ def _inherit_option(self, name: str, val: _T) -> _T: return parent_val return getattr(self.client, name) - def _advance_cluster_time(self, cluster_time: Optional[Mapping[str, Any]]) -> None: + def _advance_cluster_time(self, cluster_time: Mapping[str, Any] | None) -> None: """Internal cluster time helper.""" if self._cluster_time is None: self._cluster_time = cluster_time @@ -558,10 +557,10 @@ def advance_cluster_time(self, cluster_time: Mapping[str, Any]) -> None: f"cluster_time must be a subclass of collections.Mapping, not {type(cluster_time)}" ) if not isinstance(cluster_time.get("clusterTime"), Timestamp): - raise ValueError("Invalid cluster_time") + raise TypeError("Invalid cluster_time") self._advance_cluster_time(cluster_time) - def _advance_operation_time(self, operation_time: Optional[Timestamp]) -> None: + def _advance_operation_time(self, operation_time: Timestamp | None) -> None: """Internal operation time helper.""" if self._operation_time is None: self._operation_time = operation_time @@ -617,14 +616,14 @@ def _starting_transaction(self) -> bool: return self._transaction.starting() @property - def _pinned_address(self) -> Optional[_Address]: + def _pinned_address(self) -> _Address | None: """The mongos address this transaction was created on.""" if self._transaction.active(): return self._transaction.pinned_address return None @property - def _pinned_connection(self) -> Optional[_ConnectionT]: + def _pinned_connection(self) -> _ConnectionT | None: """The connection this transaction was started on.""" return self._transaction.pinned_conn @@ -632,14 +631,14 @@ def _pin(self, server: _AgnosticServer, conn: _ConnectionT) -> None: """Pin this session to the given Server or to the given connection.""" self._transaction.pin(server, conn) - def _txn_read_preference(self) -> Optional[_ServerMode]: + def _txn_read_preference(self) -> _ServerMode | None: """Return read preference of this transaction or None.""" if self.in_transaction: assert self._transaction.opts return self._transaction.opts.read_preference return None - def _materialize(self, logical_session_timeout_minutes: Optional[int] = None) -> None: + def _materialize(self, logical_session_timeout_minutes: int | None = None) -> None: if isinstance(self._server_session, _EmptyServerSession): old = self._server_session self._server_session = self._client._topology.get_server_session( @@ -724,7 +723,7 @@ def __copy__(self) -> NoReturn: class _ConnectionManagerProtocol(Protocol[_ConnectionT]): """Protocol for the connection manager used to pin a connection to a transaction.""" - conn: Optional[_ConnectionT] + conn: _ConnectionT | None class _TransactionBase(Generic[_ConnectionT]): @@ -733,12 +732,12 @@ class _TransactionBase(Generic[_ConnectionT]): # Set by the async/sync subclasses to the correct _ConnectionManager class. _conn_mgr_cls: Callable[[_ConnectionT, bool], _ConnectionManagerProtocol[_ConnectionT]] - def __init__(self, opts: Optional[TransactionOptions], client: _AgnosticMongoClient): + def __init__(self, opts: TransactionOptions | None, client: _AgnosticMongoClient): self.opts = opts self.state = _TxnState.NONE self.sharded = False - self.pinned_address: Optional[_Address] = None - self.conn_mgr: Optional[_ConnectionManagerProtocol[_ConnectionT]] = None + self.pinned_address: _Address | None = None + self.conn_mgr: _ConnectionManagerProtocol[_ConnectionT] | None = None self.recovery_token = None self.attempt = 0 self.client = client @@ -758,7 +757,7 @@ def set_in_progress(self) -> None: self.state = _TxnState.IN_PROGRESS @property - def pinned_conn(self) -> Optional[_ConnectionT]: + def pinned_conn(self) -> _ConnectionT | None: if self.active() and self.conn_mgr: return self.conn_mgr.conn return None @@ -775,5 +774,5 @@ def __del__(self) -> None: # Reuse the cursor closing machinery to return the socket to the # pool soon. _close_cursor_soon expects the IO-specific # _ConnectionManager, which conn_mgr is at runtime. - self.client._close_cursor_soon(0, None, cast(Any, self.conn_mgr)) + self.client._close_cursor_soon(0, None, cast("Any", self.conn_mgr)) self.conn_mgr = None diff --git a/pymongo/collation.py b/pymongo/collation.py index 9f108c447c..396560bcd2 100644 --- a/pymongo/collation.py +++ b/pymongo/collation.py @@ -21,12 +21,14 @@ from __future__ import annotations -from collections.abc import Mapping -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo import common from pymongo.write_concern import validate_boolean +if TYPE_CHECKING: + from collections.abc import Mapping + class CollationStrength: """ @@ -161,14 +163,14 @@ class Collation: def __init__( self, locale: str, - caseLevel: Optional[bool] = None, - caseFirst: Optional[str] = None, - strength: Optional[int] = None, - numericOrdering: Optional[bool] = None, - alternate: Optional[str] = None, - maxVariable: Optional[str] = None, - normalization: Optional[bool] = None, - backwards: Optional[bool] = None, + caseLevel: bool | None = None, + caseFirst: str | None = None, + strength: int | None = None, + numericOrdering: bool | None = None, + alternate: str | None = None, + maxVariable: str | None = None, + normalization: bool | None = None, + backwards: bool | None = None, **kwargs: Any, ) -> None: locale = common.validate_string("locale", locale) @@ -207,20 +209,20 @@ def __repr__(self) -> str: document = self.document return "Collation({})".format(", ".join(f"{key}={document[key]!r}" for key in document)) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Collation): return self.document == other.document return NotImplemented __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def validate_collation_or_none( - value: Optional[Union[Mapping[str, Any], Collation]], -) -> Optional[dict[str, Any]]: + value: Mapping[str, Any] | Collation | None, +) -> dict[str, Any] | None: if value is None: return None if isinstance(value, Collation): diff --git a/pymongo/common.py b/pymongo/common.py index 224b762fa5..81e3fa6d9b 100644 --- a/pymongo/common.py +++ b/pymongo/common.py @@ -27,8 +27,7 @@ TYPE_CHECKING, Any, NoReturn, - Optional, - Union, + Self, overload, ) from urllib.parse import unquote_plus @@ -106,13 +105,13 @@ MAX_CONNECTING = 2 # Default value for maxIdleTimeMS. -MAX_IDLE_TIME_MS: Optional[int] = None +MAX_IDLE_TIME_MS: int | None = None # Default value for maxIdleTimeMS in seconds. -MAX_IDLE_TIME_SEC: Optional[int] = None +MAX_IDLE_TIME_SEC: int | None = None # Default value for waitQueueTimeoutMS in seconds. -WAIT_QUEUE_TIMEOUT: Optional[int] = None +WAIT_QUEUE_TIMEOUT: int | None = None # Default value for localThresholdMS. LOCAL_THRESHOLD_MS = 15 @@ -172,7 +171,7 @@ def clean_node(node: str) -> tuple[str, int]: return host.lower(), port -def raise_config_error(key: str, suggestions: Optional[list[str]] = None) -> NoReturn: +def raise_config_error(key: str, suggestions: list[str] | None = None) -> NoReturn: """Raise ConfigurationError with the given key name.""" msg = f"Unknown option: {key}." if suggestions: @@ -227,7 +226,7 @@ def validate_non_negative_integer(option: str, value: Any) -> int: return val -def validate_readable(option: str, value: Any) -> Optional[str]: +def validate_readable(option: str, value: Any) -> str | None: """Validates that 'value' is file-like and readable.""" if value is None: return value @@ -238,7 +237,7 @@ def validate_readable(option: str, value: Any) -> Optional[str]: return value -def validate_non_negative_integer_or_none(option: str, value: Any) -> Optional[int]: +def validate_non_negative_integer_or_none(option: str, value: Any) -> int | None: """Validate that 'value' is a positive integer or 0 or None.""" if value is None: return value @@ -252,14 +251,14 @@ def validate_string(option: str, value: Any) -> str: raise TypeError(f"Wrong type for {option}, value must be an instance of str, not {type(value)}") -def validate_string_or_none(option: str, value: Any) -> Optional[str]: +def validate_string_or_none(option: str, value: Any) -> str | None: """Validates that 'value' is an instance of `basestring` or `None`.""" if value is None: return value return validate_string(option, value) -def validate_non_negative_int_or_basestring(option: Any, value: Any) -> Union[int, str]: +def validate_non_negative_int_or_basestring(option: Any, value: Any) -> int | str: """Validates that 'value' is an integer or string.""" if isinstance(value, int): return value @@ -302,7 +301,7 @@ def validate_positive_float_or_zero(option: str, value: Any) -> float: return validate_positive_float(option, value) -def validate_timeout_or_none(option: str, value: Any) -> Optional[float]: +def validate_timeout_or_none(option: str, value: Any) -> float | None: """Validates a timeout specified in milliseconds returning a value in floating point seconds. """ @@ -324,7 +323,7 @@ def validate_timeout_or_zero(option: str, value: Any) -> float: return validate_positive_float(option, value) / 1000.0 -def validate_timeout_or_none_or_zero(option: Any, value: Any) -> Optional[float]: +def validate_timeout_or_none_or_zero(option: Any, value: Any) -> float | None: """Validates a timeout specified in milliseconds returning a value in floating point seconds. value=0 and value="0" are treated the same as value=None which means unlimited timeout. @@ -334,7 +333,7 @@ def validate_timeout_or_none_or_zero(option: Any, value: Any) -> Optional[float] return validate_positive_float(option, value) / 1000.0 -def validate_timeoutms(option: Any, value: Any) -> Optional[float]: +def validate_timeoutms(option: Any, value: Any) -> float | None: """Validates a timeout specified in milliseconds returning a value in floating point seconds. """ @@ -450,12 +449,12 @@ def redact_auth_mechanism_properties_for_repr(value: Any) -> Any: return redacted -def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, Union[bool, str]]: +def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, bool | str]: """Validate authMechanismProperties.""" props: dict[str, Any] = {} if not isinstance(value, str): if not isinstance(value, dict): - raise ValueError( + raise TypeError( f"Auth mechanism properties must be given as a string or a dictionary, not {type(value)}" ) for key, value in value.items(): # noqa: B020 @@ -469,10 +468,10 @@ def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, Uni from pymongo.auth_oidc_shared import OIDCCallback if not isinstance(value, OIDCCallback): - raise ValueError(f"callback must be an OIDCCallback object, not {type(value)}") + raise TypeError(f"callback must be an OIDCCallback object, not {type(value)}") props[key] = value else: - raise ValueError(f"Invalid type for auth mechanism property {key}, {type(value)}") + raise TypeError(f"Invalid type for auth mechanism property {key}, {type(value)}") return props value = validate_string(option, value) @@ -507,7 +506,7 @@ def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, Uni def validate_document_class( option: str, value: Any -) -> Union[type[MutableMapping[str, Any]], type[RawBSONDocument]]: +) -> type[MutableMapping[str, Any] | RawBSONDocument]: """Validate the document_class option.""" # Generic aliases like SON[str, Any] or dict[str, Any] aren't classes, so # resolve to their origin before the subclass check. issubclass() raises @@ -527,7 +526,7 @@ def validate_document_class( return value -def validate_type_registry(option: Any, value: Any) -> Optional[TypeRegistry]: +def validate_type_registry(option: Any, value: Any) -> TypeRegistry | None: """Validate the type_registry option.""" if value is not None and not isinstance(value, TypeRegistry): raise TypeError(f"{option} must be an instance of {TypeRegistry}") @@ -541,7 +540,7 @@ def validate_list(option: str, value: Any) -> list[Any]: return value -def validate_list_or_none(option: Any, value: Any) -> Optional[list[Any]]: +def validate_list_or_none(option: Any, value: Any) -> list[Any] | None: """Validates that 'value' is a list or None.""" if value is None: return value @@ -579,7 +578,7 @@ def validate_is_document_type(option: str, value: Any) -> None: ) -def validate_appname_or_none(option: str, value: Any) -> Optional[str]: +def validate_appname_or_none(option: str, value: Any) -> str | None: """Validate the appname option.""" if value is None: return value @@ -590,7 +589,7 @@ def validate_appname_or_none(option: str, value: Any) -> Optional[str]: return value -def validate_driver_or_none(option: Any, value: Any) -> Optional[DriverInfo]: +def validate_driver_or_none(option: Any, value: Any) -> DriverInfo | None: """Validate the driver keyword arg.""" if value is None: return value @@ -599,7 +598,7 @@ def validate_driver_or_none(option: Any, value: Any) -> Optional[DriverInfo]: return value -def validate_server_api_or_none(option: Any, value: Any) -> Optional[ServerApi]: +def validate_server_api_or_none(option: Any, value: Any) -> ServerApi | None: """Validate the server_api keyword arg.""" if value is None: return value @@ -608,12 +607,12 @@ def validate_server_api_or_none(option: Any, value: Any) -> Optional[ServerApi]: return value -def validate_is_callable_or_none(option: Any, value: Any) -> Optional[Callable[..., Any]]: +def validate_is_callable_or_none(option: Any, value: Any) -> Callable[..., Any] | None: """Validates that 'value' is a callable.""" if value is None: return value if not callable(value): - raise ValueError(f"{option} must be a callable, not {type(value)}") + raise TypeError(f"{option} must be a callable, not {type(value)}") return value @@ -654,14 +653,14 @@ def validate_unicode_decode_error_handler(dummy: Any, value: str) -> str: return value -def validate_tzinfo(dummy: Any, value: Any) -> Optional[datetime.tzinfo]: +def validate_tzinfo(dummy: Any, value: Any) -> datetime.tzinfo | None: """Validate the tzinfo option""" if value is not None and not isinstance(value, datetime.tzinfo): raise TypeError(f"{value} must be an instance of datetime.tzinfo") return value -def validate_auto_encryption_opts_or_none(option: Any, value: Any) -> Optional[Any]: +def validate_auto_encryption_opts_or_none(option: Any, value: Any) -> Any | None: """Validate the driver keyword arg.""" if value is None: return value @@ -673,7 +672,7 @@ def validate_auto_encryption_opts_or_none(option: Any, value: Any) -> Optional[A return value -def validate_datetime_conversion(option: Any, value: Any) -> Optional[DatetimeConversion]: +def validate_datetime_conversion(option: Any, value: Any) -> DatetimeConversion | None: """Validate a DatetimeConversion string.""" if value is None: return DatetimeConversion.DATETIME @@ -835,7 +834,7 @@ def validate_server_monitoring_mode(option: str, value: str) -> str: def _get_validator( - key: str, validators: dict[str, Callable[[Any, Any], Any]], normed_key: Optional[str] = None + key: str, validators: dict[str, Callable[[Any, Any], Any]], normed_key: str | None = None ) -> Callable[[Any, Any], Any]: normed_key = normed_key or key try: @@ -970,7 +969,7 @@ def write_concern(self) -> WriteConcern: """ return self._write_concern - def _write_concern_for(self, session: Optional[_AgnosticClientSession]) -> WriteConcern: + def _write_concern_for(self, session: _AgnosticClientSession | None) -> WriteConcern: """Read only access to the write concern of this instance or session.""" # Override this operation's write concern with the transaction's. if session and session.in_transaction: @@ -978,7 +977,7 @@ def _write_concern_for(self, session: Optional[_AgnosticClientSession]) -> Write return self.write_concern def _write_concern_for_cmd( - self, cmd: Mapping[str, Any], session: Optional[_AgnosticClientSession] + self, cmd: Mapping[str, Any], session: _AgnosticClientSession | None ) -> WriteConcern: raw_wc = cmd.get("writeConcern") if raw_wc is not None: @@ -995,7 +994,7 @@ def read_preference(self) -> _ServerMode: """ return self._read_preference - def _read_preference_for(self, session: Optional[_AgnosticClientSession]) -> _ServerMode: + def _read_preference_for(self, session: _AgnosticClientSession | None) -> _ServerMode: """Read only access to the read preference of this instance or session.""" # Override this operation's read preference with the transaction's. if session: @@ -1043,7 +1042,7 @@ def __delitem__(self, key: str) -> None: del self.__casedkeys[lc_key] del self.__data[lc_key] - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if not isinstance(other, abc.Mapping): return NotImplemented if len(self) != len(other): @@ -1056,7 +1055,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore[assignment] - def get(self, key: str, default: Optional[Any] = None) -> Any: + def get(self, key: str, default: Any | None = None) -> Any: return self.__data.get(key.lower(), default) def pop(self, key: str, *args: Any, **kwargs: Any) -> Any: @@ -1074,12 +1073,12 @@ def clear(self) -> None: self.__data.clear() @overload - def setdefault(self, key: str, default: None = None) -> Optional[Any]: ... + def setdefault(self, key: str, default: None = None) -> Any | None: ... @overload def setdefault(self, key: str, default: Any) -> Any: ... - def setdefault(self, key: str, default: Optional[Any] = None) -> Optional[Any]: + def setdefault(self, key: str, default: Any | None = None) -> Any | None: lc_key = key.lower() if key in self: return self.__data[lc_key] @@ -1113,7 +1112,7 @@ def has_c() -> bool: class Version(tuple[int, ...]): """A class that can be used to compare version strings.""" - def __new__(cls, *version: int) -> Version: + def __new__(cls, *version: int) -> Self: padded_version = cls._padded(version, 4) return super().__new__(cls, tuple(padded_version)) @@ -1121,8 +1120,7 @@ def __new__(cls, *version: int) -> Version: def _padded(cls, iter: Any, length: int, padding: int = 0) -> list[int]: as_list = list(iter) if len(as_list) < length: - for _ in range(length - len(as_list)): - as_list.append(padding) + as_list.extend(padding for _ in range(length - len(as_list))) return as_list @classmethod diff --git a/pymongo/compression_support.py b/pymongo/compression_support.py index 39f0834a8c..84ef43e6f2 100644 --- a/pymongo/compression_support.py +++ b/pymongo/compression_support.py @@ -15,13 +15,15 @@ import sys import warnings -from collections.abc import Iterable -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo.errors import ProtocolError from pymongo.hello import HelloCompat from pymongo.helpers_shared import _SENSITIVE_COMMANDS +if TYPE_CHECKING: + from collections.abc import Iterable + _SUPPORTED_COMPRESSORS = {"snappy", "zlib", "zstd"} _NO_COMPRESSION = {HelloCompat.CMD, HelloCompat.LEGACY_CMD} _NO_COMPRESSION.update(_SENSITIVE_COMMANDS) @@ -57,7 +59,7 @@ def _have_zstd() -> bool: return False -def validate_compressors(dummy: Any, value: Union[str, Iterable[str]]) -> list[str]: +def validate_compressors(dummy: Any, value: str | Iterable[str]) -> list[str]: try: # `value` is string. compressors = value.split(",") # type: ignore[union-attr] @@ -116,8 +118,8 @@ def __init__(self, compressors: list[str], zlib_compression_level: int): self.zlib_compression_level = zlib_compression_level def get_compression_context( - self, compressors: Optional[list[str]] - ) -> Union[SnappyContext, ZlibContext, ZstdContext, None]: + self, compressors: list[str] | None + ) -> SnappyContext | ZlibContext | ZstdContext | None: if compressors: chosen = compressors[0] if chosen == "snappy": diff --git a/pymongo/cursor_shared.py b/pymongo/cursor_shared.py index 3a0acbe932..6fdf784750 100644 --- a/pymongo/cursor_shared.py +++ b/pymongo/cursor_shared.py @@ -22,7 +22,7 @@ from abc import ABC, abstractmethod from collections import deque from collections.abc import Iterable, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Generic, Optional, Union, cast, overload +from typing import TYPE_CHECKING, Any, Generic, cast, overload from bson import RE_TYPE from bson.code import Code @@ -55,7 +55,7 @@ def _split_message( - message: Union[tuple[int, bytes], tuple[int, bytes, int]], + message: tuple[int, bytes] | tuple[int, bytes, int], ) -> tuple[int, bytes, int]: """Return request_id, data, max_doc_size. @@ -68,7 +68,7 @@ def _split_message( return request_id, data, 0 -class _AgnosticCursorBase(Generic[_DocumentType], ABC): +class _AgnosticCursorBase(ABC, Generic[_DocumentType]): """ Shared IO-agnostic cursor base used by both async and sync cursor classes. All IO-specific behavior is implemented in subclasses. @@ -76,11 +76,11 @@ class _AgnosticCursorBase(Generic[_DocumentType], ABC): # These are all typed more accurately in subclasses. _collection: Any - _id: Optional[int] + _id: int | None _data: Any - _address: Optional[_Address] + _address: _Address | None _sock_mgr: Any - _session: Optional[Any] + _session: Any | None _killed: bool @abstractmethod @@ -89,7 +89,7 @@ def _get_namespace(self) -> str: ... @property - def session(self) -> Optional[_AgnosticClientSession]: + def session(self) -> _AgnosticClientSession | None: """The cursor's session, or None if the session is implicit. Typed more accurately in subclasses. @@ -131,7 +131,7 @@ def alive(self) -> bool: return bool(len(self._data) or (not self._killed)) @property - def cursor_id(self) -> Optional[int]: + def cursor_id(self) -> int | None: """Returns the id of the cursor. .. versionadded:: 2.2 @@ -139,7 +139,7 @@ def cursor_id(self) -> Optional[int]: return self._id @property - def address(self) -> Optional[_Address]: + def address(self) -> _Address | None: """The (host, port) of the server used, or None. .. versionchanged:: 3.0 @@ -147,7 +147,7 @@ def address(self) -> Optional[_Address]: """ return self._address - def _prepare_to_die(self, already_killed: bool) -> tuple[int, Optional[_CursorAddress]]: + def _prepare_to_die(self, already_killed: bool) -> tuple[int, _CursorAddress | None]: self._killed = True if self._id and not already_killed: cursor_id = self._id @@ -192,10 +192,10 @@ def __init__( self, collection: _AgnosticCollection[_DocumentType], cursor_info: Mapping[str, Any], - address: Optional[_Address], + address: _Address | None, batch_size: int = 0, - max_await_time_ms: Optional[int] = None, - session: Optional[_AgnosticClientSession] = None, + max_await_time_ms: int | None = None, + session: _AgnosticClientSession | None = None, comment: Any = None, ) -> None: """Create a new command cursor.""" @@ -203,7 +203,7 @@ def __init__( self._collection = collection self._id = cursor_info["id"] self._data = deque(cursor_info["firstBatch"]) - self._postbatchresumetoken: Optional[Mapping[str, Any]] = cursor_info.get( + self._postbatchresumetoken: Mapping[str, Any] | None = cursor_info.get( "postBatchResumeToken" ) self._address = address @@ -263,7 +263,7 @@ def _has_next(self) -> bool: return len(self._data) > 0 @property - def _post_batch_resume_token(self) -> Optional[Mapping[str, Any]]: + def _post_batch_resume_token(self) -> Mapping[str, Any] | None: """Retrieve the postBatchResumeToken from the response to a changeStream aggregate or getMore. """ @@ -272,9 +272,9 @@ def _post_batch_resume_token(self) -> Optional[Mapping[str, Any]]: def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions[Mapping[str, Any]], - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> Sequence[_DocumentOut]: return response.unpack_response(cursor_id, codec_options, user_fields, legacy_response) @@ -356,10 +356,8 @@ class CursorType: """ -_Sort = Union[ - Sequence[Union[str, tuple[str, Union[int, str, Mapping[str, Any]]]]], Mapping[str, Any] -] -_Hint = Union[str, _Sort] +_Sort = Sequence[str | tuple[str, int | str | Mapping[str, Any]]] | Mapping[str, Any] +_Hint = str | _Sort class _AgnosticCursor(_AgnosticCursorBase[_DocumentType]): @@ -374,29 +372,29 @@ class _AgnosticCursor(_AgnosticCursorBase[_DocumentType]): def __init__( self, collection: _AgnosticCollection[_DocumentType], - filter: Optional[Mapping[str, Any]] = None, - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, + filter: Mapping[str, Any] | None = None, + projection: Mapping[str, Any] | Iterable[str] | None = None, skip: int = 0, limit: int = 0, no_cursor_timeout: bool = False, cursor_type: int = CursorType.NON_TAILABLE, - sort: Optional[_Sort] = None, + sort: _Sort | None = None, allow_partial_results: bool = False, oplog_replay: bool = False, batch_size: int = 0, - collation: Optional[_CollationIn] = None, - hint: Optional[_Hint] = None, - max_scan: Optional[int] = None, - max_time_ms: Optional[int] = None, - max: Optional[_Sort] = None, - min: Optional[_Sort] = None, - return_key: Optional[bool] = None, - show_record_id: Optional[bool] = None, - snapshot: Optional[bool] = None, - comment: Optional[Any] = None, - session: Optional[_AgnosticClientSession] = None, - allow_disk_use: Optional[bool] = None, - let: Optional[Mapping[str, Any]] = None, + collation: _CollationIn | None = None, + hint: _Hint | None = None, + max_scan: int | None = None, + max_time_ms: int | None = None, + max: _Sort | None = None, + min: _Sort | None = None, + return_key: bool | None = None, + show_record_id: bool | None = None, + snapshot: bool | None = None, + comment: Any | None = None, + session: _AgnosticClientSession | None = None, + allow_disk_use: bool | None = None, + let: Mapping[str, Any] | None = None, ) -> None: """Create a new cursor. Used by a collection's ``find()`` method to iterate over MongoDB query results. @@ -473,15 +471,15 @@ def __init__( self._comment = comment self._max_time_ms = max_time_ms self._timeout = self._collection.database.client.options.timeout - self._max_await_time_ms: Optional[int] = None - self._max: Optional[Union[dict[Any, Any], _Sort]] = max - self._min: Optional[Union[dict[Any, Any], _Sort]] = min + self._max_await_time_ms: int | None = None + self._max: dict[Any, Any] | _Sort | None = max + self._min: dict[Any, Any] | _Sort | None = min self._collation = validate_collation_or_none(collation) self._return_key = return_key self._show_record_id = show_record_id self._allow_disk_use = allow_disk_use self._snapshot = snapshot - self._hint: Union[str, dict[str, Any], None] + self._hint: str | dict[str, Any] | None self._set_hint(hint) # This is ugly. People want to be able to do cursor[5:5] and @@ -493,12 +491,12 @@ def __init__( self._empty = False self._data: deque = deque() # type: ignore[type-arg] - self._address: Optional[_Address] = None + self._address: _Address | None = None self._retrieved = 0 self._codec_options = collection.codec_options # Read preference is set when the initial find is sent. - self._read_preference: Optional[_ServerMode] = None + self._read_preference: _ServerMode | None = None self._read_concern = collection.read_concern self._query_flags = cursor_type @@ -545,7 +543,7 @@ def clone(self) -> Self: """ return self._clone(True) - def _clone(self, deepcopy: bool = True, base: Optional[Any] = None) -> Self: + def _clone(self, deepcopy: bool = True, base: Any | None = None) -> Self: """Internal clone helper.""" if not base: if self._session and not self._session._implicit: @@ -587,7 +585,7 @@ def _clone(self, deepcopy: bool = True, base: Optional[Any] = None) -> Self: base.__dict__.update(data) return base - def _clone_base(self, session: Optional[Any]) -> Self: + def _clone_base(self, session: Any | None) -> Self: """Creates an empty cursor object for information to be copied into.""" return self.__class__(self._collection, session=session) @@ -752,7 +750,7 @@ def skip(self, skip: int) -> Self: self._skip = skip return self - def max_time_ms(self, max_time_ms: Optional[int]) -> Self: + def max_time_ms(self, max_time_ms: int | None) -> Self: """Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms` @@ -771,7 +769,7 @@ def max_time_ms(self, max_time_ms: Optional[int]) -> Self: self._max_time_ms = max_time_ms return self - def max_await_time_ms(self, max_await_time_ms: Optional[int]) -> Self: + def max_await_time_ms(self, max_await_time_ms: int | None) -> Self: """Specifies a time limit for a getMore operation on a :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other types of cursor max_await_time_ms is ignored. @@ -799,7 +797,7 @@ def max_await_time_ms(self, max_await_time_ms: Optional[int]) -> Self: return self - def max_scan(self, max_scan: Optional[int]) -> Self: + def max_scan(self, max_scan: int | None) -> Self: """**DEPRECATED** - Limit the number of documents to scan when performing the query. @@ -860,7 +858,7 @@ def min(self, spec: _Sort) -> Self: self._min = dict(spec) return self - def sort(self, key_or_list: _Hint, direction: Optional[Union[int, str]] = None) -> Self: + def sort(self, key_or_list: _Hint, direction: int | str | None = None) -> Self: """Sorts this cursor's results. Pass a field name and a direction, either @@ -923,7 +921,7 @@ def sort(self, key_or_list: _Hint, direction: Optional[Union[int, str]] = None) self._ordering = helpers_shared._index_document(keys) return self - def _set_hint(self, index: Optional[_Hint]) -> None: + def _set_hint(self, index: _Hint | None) -> None: if index is None: self._hint = None return @@ -933,7 +931,7 @@ def _set_hint(self, index: Optional[_Hint]) -> None: else: self._hint = helpers_shared._index_document(index) - def hint(self, index: Optional[_Hint]) -> Self: + def hint(self, index: _Hint | None) -> Self: """Adds a 'hint', telling Mongo the proper index to use for the query. Judicious use of hints can greatly improve query @@ -970,7 +968,7 @@ def comment(self, comment: Any) -> Self: self._comment = comment return self - def where(self, code: Union[str, Code]) -> Self: + def where(self, code: str | Code) -> Self: """Adds a `$where`_ clause to this query. The `code` argument must be an instance of :class:`str` or @@ -1012,12 +1010,12 @@ def where(self, code: Union[str, Code]) -> Self: if self._has_filter: spec = dict(self._spec) else: - spec = cast(dict, self._spec) # type: ignore[type-arg] + spec = cast("dict", self._spec) # type: ignore[type-arg] spec["$where"] = code self._spec = spec return self - def collation(self, collation: Optional[_CollationIn]) -> Self: + def collation(self, collation: _CollationIn | None) -> Self: """Adds a :class:`~pymongo.collation.Collation` to this query. Raises :exc:`TypeError` if `collation` is not an instance of @@ -1035,9 +1033,9 @@ def collation(self, collation: Optional[_CollationIn]) -> Self: def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions, # type: ignore[type-arg] - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> Sequence[_DocumentOut]: return response.unpack_response(cursor_id, codec_options, user_fields, legacy_response) @@ -1063,28 +1061,28 @@ def __deepcopy__(self, memo: Any) -> Any: return self._clone(deepcopy=True) @overload - def _deepcopy(self, x: Iterable, memo: Optional[dict[int, Union[list, dict]]] = None) -> list: # type: ignore[type-arg] + def _deepcopy(self, x: Iterable, memo: dict[int, list | dict] | None = None) -> list: # type: ignore[type-arg] ... @overload def _deepcopy( self, x: SupportsItems, # type: ignore[type-arg] - memo: Optional[dict[int, Union[list, dict]]] = None, # type: ignore[type-arg] + memo: dict[int, list | dict] | None = None, # type: ignore[type-arg] ) -> dict: # type: ignore[type-arg] ... def _deepcopy( self, - x: Union[Iterable, SupportsItems], # type: ignore[type-arg] - memo: Optional[dict[int, Union[list, dict]]] = None, # type: ignore[type-arg] - ) -> Union[list[Any], dict[str, Any]]: + x: Iterable | SupportsItems, # type: ignore[type-arg] + memo: dict[int, list | dict] | None = None, # type: ignore[type-arg] + ) -> list[Any] | dict[str, Any]: """Deepcopy helper for the data dictionary or list. Regular expressions cannot be deep copied but as they are immutable we don't have to copy them when cloning. """ - y: Union[list[Any], dict[str, Any]] + y: list[Any] | dict[str, Any] iterator: Iterable[tuple[Any, Any]] if not hasattr(x, "items"): y, is_list, iterator = [], True, enumerate(x) diff --git a/pymongo/daemon.py b/pymongo/daemon.py index 90e8fa42fc..756ea53423 100644 --- a/pymongo/daemon.py +++ b/pymongo/daemon.py @@ -25,15 +25,17 @@ import subprocess import sys import warnings -from collections.abc import Sequence -from typing import Any, Optional +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Sequence # The maximum amount of time to wait for the intermediate subprocess. _WAIT_TIMEOUT = 10 _THIS_FILE = os.path.realpath(__file__) -def _popen_wait(popen: subprocess.Popen[Any], timeout: Optional[float]) -> Optional[int]: +def _popen_wait(popen: subprocess.Popen[Any], timeout: float | None) -> int | None: """Implement wait timeout support for Python 3.""" try: return popen.wait(timeout=timeout) @@ -42,7 +44,7 @@ def _popen_wait(popen: subprocess.Popen[Any], timeout: Optional[float]) -> Optio return None -def _silence_resource_warning(popen: Optional[subprocess.Popen[Any]]) -> None: +def _silence_resource_warning(popen: subprocess.Popen[Any] | None) -> None: """Silence Popen's ResourceWarning. Note this should only be used if the process was created as a daemon. @@ -91,7 +93,7 @@ def _spawn_daemon(args: Sequence[str]) -> None: # to be safe to call from any thread. Using Popen instead of fork also # avoids triggering the application's os.register_at_fork() callbacks when # we spawn the mongocryptd daemon process. - def _spawn(args: Sequence[str]) -> Optional[subprocess.Popen[Any]]: + def _spawn(args: Sequence[str]) -> subprocess.Popen[Any] | None: """Spawn the process and silence stdout/stderr.""" try: with open(os.devnull, "r+b") as devnull: diff --git a/pymongo/database_shared.py b/pymongo/database_shared.py index 8bbf04f29c..e451f49478 100644 --- a/pymongo/database_shared.py +++ b/pymongo/database_shared.py @@ -33,4 +33,4 @@ def _check_name(name: str) -> None: raise InvalidName(f"database names cannot contain the character {invalid_char!r}") -_CodecDocumentType = TypeVar("_CodecDocumentType", bound=Mapping[str, Any]) +_CodecDocumentType = TypeVar("_CodecDocumentType", bound=Mapping[str, Any]) # noqa: PYI018 diff --git a/pymongo/driver_info.py b/pymongo/driver_info.py index a325ea1493..73a190c470 100644 --- a/pymongo/driver_info.py +++ b/pymongo/driver_info.py @@ -20,7 +20,7 @@ from __future__ import annotations from collections import namedtuple -from typing import Optional +from typing import Self class DriverInfo(namedtuple("DriverInfo", ["name", "version", "platform"])): @@ -39,9 +39,7 @@ class DriverInfo(namedtuple("DriverInfo", ["name", "version", "platform"])): :class:`ValueError` is raised if it does. """ - def __new__( - cls, name: str, version: Optional[str] = None, platform: Optional[str] = None - ) -> DriverInfo: + def __new__(cls, name: str, version: str | None = None, platform: str | None = None) -> Self: self = super().__new__(cls, name, version, platform) for key, value in self._asdict().items(): if value is not None and not isinstance(value, str): diff --git a/pymongo/encryption_options.py b/pymongo/encryption_options.py index f02b28e9b8..acc3df348a 100644 --- a/pymongo/encryption_options.py +++ b/pymongo/encryption_options.py @@ -19,9 +19,7 @@ from __future__ import annotations -import warnings -from collections.abc import Callable, Mapping -from typing import TYPE_CHECKING, Any, Optional, TypedDict +from typing import TYPE_CHECKING, Any, TypedDict from pymongo.uri_parser_shared import _parse_kms_tls_options @@ -40,12 +38,14 @@ AsyncKMSConnectCallback, HTTPProxyKMSConnect, KMSConnectCallback, - KMSConnectContext, + KMSConnectContext, # noqa: TC001 ) from pymongo.common import check_for_min_version, validate_is_mapping from pymongo.errors import ConfigurationError if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from pymongo.pyopenssl_context import SSLContext from pymongo.typings import _AgnosticMongoClient @@ -69,20 +69,20 @@ def __init__( self, kms_providers: Mapping[str, Any], key_vault_namespace: str, - key_vault_client: Optional[_AgnosticMongoClient] = None, - schema_map: Optional[Mapping[str, Any]] = None, + key_vault_client: _AgnosticMongoClient | None = None, + schema_map: Mapping[str, Any] | None = None, bypass_auto_encryption: bool = False, mongocryptd_uri: str = "mongodb://localhost:27020", mongocryptd_bypass_spawn: bool = False, mongocryptd_spawn_path: str = "mongocryptd", - mongocryptd_spawn_args: Optional[list[str]] = None, - kms_tls_options: Optional[Mapping[str, Any]] = None, - crypt_shared_lib_path: Optional[str] = None, + mongocryptd_spawn_args: list[str] | None = None, + kms_tls_options: Mapping[str, Any] | None = None, + crypt_shared_lib_path: str | None = None, crypt_shared_lib_required: bool = False, bypass_query_analysis: bool = False, - encrypted_fields_map: Optional[Mapping[str, Any]] = None, - key_expiration_ms: Optional[int] = None, - kms_connect_callback: Optional[Callable[[KMSConnectContext], Any]] = None, + encrypted_fields_map: Mapping[str, Any] | None = None, + key_expiration_ms: int | None = None, + kms_connect_callback: Callable[[KMSConnectContext], Any] | None = None, ) -> None: """Options to configure automatic client-side field level encryption. @@ -274,8 +274,8 @@ def __init__( self._mongocryptd_spawn_args.append("--idleShutdownTimeoutSecs=60") # Maps KMS provider name to a SSLContext. self._kms_tls_options = kms_tls_options - self._sync_kms_ssl_contexts: Optional[dict[str, SSLContext]] = None - self._async_kms_ssl_contexts: Optional[dict[str, SSLContext]] = None + self._sync_kms_ssl_contexts: dict[str, SSLContext] | None = None + self._async_kms_ssl_contexts: dict[str, SSLContext] | None = None self._bypass_query_analysis = bypass_query_analysis self._key_expiration_ms = key_expiration_ms if kms_connect_callback is not None and not callable(kms_connect_callback): @@ -300,11 +300,11 @@ class RangeOpts: def __init__( self, - sparsity: Optional[int] = None, - trim_factor: Optional[int] = None, - min: Optional[Any] = None, - max: Optional[Any] = None, - precision: Optional[int] = None, + sparsity: int | None = None, + trim_factor: int | None = None, + min: Any | None = None, + max: Any | None = None, + precision: int | None = None, ) -> None: """Options to configure encrypted queries using the range algorithm. @@ -324,17 +324,17 @@ def __init__( @property def document(self) -> dict[str, Any]: - doc = {} - for k, v in [ - ("sparsity", int64.Int64(self.sparsity) if self.sparsity else None), - ("trimFactor", self.trim_factor), - ("precision", self.precision), - ("min", self.min), - ("max", self.max), - ]: - if v is not None: - doc[k] = v - return doc + return { + k: v + for k, v in [ + ("sparsity", int64.Int64(self.sparsity) if self.sparsity else None), + ("trimFactor", self.trim_factor), + ("precision", self.precision), + ("min", self.min), + ("max", self.max), + ] + if v is not None + } class StringOpts: @@ -342,11 +342,11 @@ class StringOpts: def __init__( self, - substring: Optional[SubstringOpts] = None, - prefix: Optional[PrefixOpts] = None, - suffix: Optional[SuffixOpts] = None, - case_sensitive: Optional[bool] = None, - diacritic_sensitive: Optional[bool] = None, + substring: SubstringOpts | None = None, + prefix: PrefixOpts | None = None, + suffix: SuffixOpts | None = None, + case_sensitive: bool | None = None, + diacritic_sensitive: bool | None = None, ) -> None: """Options to configure encrypted queries using the string algorithm. @@ -357,7 +357,6 @@ def __init__( :param diacritic_sensitive: Whether string indexes for this field are diacritic sensitive. .. versionadded:: 4.18 - ``StringOpts`` replaces ``TextOpts``, which is deprecated. """ self.substring = substring self.prefix = prefix @@ -367,17 +366,17 @@ def __init__( @property def document(self) -> dict[str, Any]: - doc = {} - for k, v in [ - ("substring", self.substring), - ("prefix", self.prefix), - ("suffix", self.suffix), - ("caseSensitive", self.case_sensitive), - ("diacriticSensitive", self.diacritic_sensitive), - ]: - if v is not None: - doc[k] = v - return doc + return { + k: v + for k, v in [ + ("substring", self.substring), + ("prefix", self.prefix), + ("suffix", self.suffix), + ("caseSensitive", self.case_sensitive), + ("diacriticSensitive", self.diacritic_sensitive), + ] + if v is not None + } class SubstringOpts(TypedDict): @@ -416,29 +415,3 @@ class SuffixOpts(TypedDict): strMinQueryLength: int # strMaxQueryLength is the maximum allowed query length. Querying with a longer string will error. strMaxQueryLength: int - - -class TextOpts(StringOpts): - """**DEPRECATED** Options to configure encrypted queries using the text algorithm. - - .. note:: ``TextOpts`` is deprecated. Use :class:`StringOpts` instead. - ``TextOpts`` corresponds to the ``text_opts`` parameter of - :meth:`~pymongo.encryption.ClientEncryption.encrypt`, which pymongocrypt - added in 1.16 and renamed to ``string_opts`` in 1.19. Passing - ``TextOpts`` as ``text_opts`` therefore only works with pymongocrypt - 1.16 through 1.18; with pymongocrypt 1.19 or later, pass - :class:`StringOpts` as ``string_opts``. - - .. versionadded:: 4.15 - - .. versionchanged:: 4.18 - Deprecated in favor of :class:`StringOpts`. - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - warnings.warn( - "TextOpts is deprecated. Use StringOpts instead.", - DeprecationWarning, - stacklevel=2, - ) - super().__init__(*args, **kwargs) diff --git a/pymongo/encryption_shared.py b/pymongo/encryption_shared.py index 08c65510d0..28909f428b 100644 --- a/pymongo/encryption_shared.py +++ b/pymongo/encryption_shared.py @@ -19,7 +19,7 @@ import contextlib import enum from collections.abc import Iterator -from typing import Any, Optional +from typing import TYPE_CHECKING, Any try: from pymongocrypt.mongocrypt import MongoCryptOptions # type:ignore[import-untyped] @@ -28,7 +28,12 @@ from bson.errors import BSONError from pymongo.errors import EncryptionError -from pymongo.results import BulkWriteResult + +if TYPE_CHECKING: + from pymongo.results import BulkWriteResult + +if TYPE_CHECKING: + from collections.abc import Iterator @contextlib.contextmanager @@ -51,11 +56,11 @@ class RewrapManyDataKeyResult: .. versionadded:: 4.2 """ - def __init__(self, bulk_write_result: Optional[BulkWriteResult] = None) -> None: + def __init__(self, bulk_write_result: BulkWriteResult | None = None) -> None: self._bulk_write_result = bulk_write_result @property - def bulk_write_result(self) -> Optional[BulkWriteResult]: + def bulk_write_result(self) -> BulkWriteResult | None: """The result of the bulk write operation used to update the key vault collection with one or more rewrapped data keys. If :meth:`~pymongo.encryption.ClientEncryption.rewrap_many_data_key` or :meth:`~pymongo.asynchronous.encryption.AsyncClientEncryption.rewrap_many_data_key` does not @@ -107,6 +112,10 @@ class Algorithm(str, enum.Enum): class QueryType(str, enum.Enum): """An enum that defines the supported values for explicit encryption query_type. + .. versionchanged:: 4.20 + Removed the beta query types ``PREFIXPREVIEW``, ``SUFFIXPREVIEW``, + and ``SUBSTRINGPREVIEW``. + .. versionadded:: 4.2 """ @@ -143,36 +152,6 @@ class QueryType(str, enum.Enum): .. versionadded:: 4.18 """ - PREFIXPREVIEW = "prefixPreview" - """**BETA** - Used to encrypt a value for a prefixPreview query. - - .. note:: The preview query types are for experimental workloads only and - are only supported by MongoDB versions before 9.0. Use - :attr:`QueryType.PREFIX` instead. - - .. versionadded:: 4.15 - """ - - SUFFIXPREVIEW = "suffixPreview" - """**BETA** - Used to encrypt a value for a suffixPreview query. - - .. note:: The preview query types are for experimental workloads only and - are only supported by MongoDB versions before 9.0. Use - :attr:`QueryType.SUFFIX` instead. - - .. versionadded:: 4.15 - """ - - SUBSTRINGPREVIEW = "substringPreview" - """**BETA** - Used to encrypt a value for a substringPreview query. - - .. note:: The preview query types are for experimental workloads only and - are only supported by MongoDB versions before 9.0. Use - :attr:`QueryType.SUBSTRING` instead. - - .. versionadded:: 4.15 - """ - def _create_mongocrypt_options(**kwargs: Any) -> MongoCryptOptions: # For compat with pymongocrypt <1.13, avoid setting the default key_expiration_ms. diff --git a/pymongo/errors.py b/pymongo/errors.py index e66d53cd5f..70d436923c 100644 --- a/pymongo/errors.py +++ b/pymongo/errors.py @@ -19,13 +19,14 @@ from __future__ import annotations -from collections.abc import Iterable, Mapping, Sequence from ssl import SSLCertVerificationError as _CertificateError # noqa: F401 -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any from bson.errors import InvalidDocument if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + from pymongo.results import ClientBulkWriteResult from pymongo.typings import _DocumentOut @@ -33,7 +34,7 @@ class PyMongoError(Exception): """Base class for all PyMongo exceptions.""" - def __init__(self, message: str = "", error_labels: Optional[Iterable[str]] = None) -> None: + def __init__(self, message: str = "", error_labels: Iterable[str] | None = None) -> None: super().__init__(message) self._message = message self._error_labels = set(error_labels or []) @@ -96,11 +97,11 @@ class AutoReconnect(ConnectionFailure): Subclass of :exc:`~pymongo.errors.ConnectionFailure`. """ - errors: Union[Mapping[str, Any], Sequence[Any]] - details: Union[Mapping[str, Any], Sequence[Any]] + errors: Mapping[str, Any] | Sequence[Any] + details: Mapping[str, Any] | Sequence[Any] def __init__( - self, message: str = "", errors: Optional[Union[Mapping[str, Any], Sequence[Any]]] = None + self, message: str = "", errors: Mapping[str, Any] | Sequence[Any] | None = None ) -> None: error_labels = None if errors is not None: @@ -124,9 +125,7 @@ def timeout(self) -> bool: return True -def _format_detailed_error( - message: str, details: Optional[Union[Mapping[str, Any], list[Any]]] -) -> str: +def _format_detailed_error(message: str, details: Mapping[str, Any] | list[Any] | None) -> str: if details is not None: message = f"{message}, full error: {details}" return message @@ -149,7 +148,7 @@ class NotPrimaryError(AutoReconnect): """ def __init__( - self, message: str = "", errors: Optional[Union[Mapping[str, Any], list[Any]]] = None + self, message: str = "", errors: Mapping[str, Any] | list[Any] | None = None ) -> None: super().__init__(_format_detailed_error(message, errors), errors=errors) @@ -185,9 +184,9 @@ class OperationFailure(PyMongoError): def __init__( self, error: str, - code: Optional[int] = None, - details: Optional[Mapping[str, Any]] = None, - max_wire_version: Optional[int] = None, + code: int | None = None, + details: Mapping[str, Any] | None = None, + max_wire_version: int | None = None, ) -> None: error_labels = None base_backoff_ms = None @@ -201,16 +200,16 @@ def __init__( self.__base_backoff_ms = base_backoff_ms @property - def _max_wire_version(self) -> Optional[int]: + def _max_wire_version(self) -> int | None: return self.__max_wire_version @property - def code(self) -> Optional[int]: + def code(self) -> int | None: """The error code returned by the server, if any.""" return self.__code @property - def details(self) -> Optional[Mapping[str, Any]]: + def details(self) -> Mapping[str, Any] | None: """The complete error document returned by the server. Depending on the error that occurred, the error document @@ -226,7 +225,7 @@ def timeout(self) -> bool: return self.__code in (50,) @property - def _base_backoff_ms(self) -> Optional[float]: + def _base_backoff_ms(self) -> float | None: return self.__base_backoff_ms @@ -330,7 +329,7 @@ def __reduce__(self) -> tuple[Any, Any]: return self.__class__, (self.details,) @property - def error(self) -> Optional[Any]: + def error(self) -> Any | None: """A top-level error that occurred when attempting to communicate with the server or execute the bulk write. @@ -340,7 +339,7 @@ def error(self) -> Optional[Any]: return self.details.get("error", None) @property - def write_concern_errors(self) -> Optional[list[WriteConcernError]]: + def write_concern_errors(self) -> list[WriteConcernError] | None: """Write concern errors that occurred during the bulk write. This list may have multiple items if more than one @@ -349,7 +348,7 @@ def write_concern_errors(self) -> Optional[list[WriteConcernError]]: return self.details.get("writeConcernErrors", []) @property - def write_errors(self) -> Optional[list[WriteError]]: + def write_errors(self) -> list[WriteError] | None: """Errors that occurred during the execution of individual write operations. This list will contain at most one entry if the bulk write was ordered. @@ -357,7 +356,7 @@ def write_errors(self) -> Optional[list[WriteError]]: return self.details.get("writeErrors", {}) @property - def partial_result(self) -> Optional[ClientBulkWriteResult]: + def partial_result(self) -> ClientBulkWriteResult | None: """The results of any successful operations that were performed before the error was encountered. """ diff --git a/pymongo/hello.py b/pymongo/hello.py index a6519eed8d..b567df747e 100644 --- a/pymongo/hello.py +++ b/pymongo/hello.py @@ -17,16 +17,19 @@ from __future__ import annotations import copy -import datetime import itertools -from collections.abc import Mapping -from typing import Any, Generic, Optional +from typing import TYPE_CHECKING, Any, Generic -from bson.objectid import ObjectId from pymongo import common from pymongo.server_type import SERVER_TYPE from pymongo.typings import ClusterTime, _DocumentType +if TYPE_CHECKING: + import datetime + from collections.abc import Mapping + + from bson.objectid import ObjectId + def _get_server_type(doc: Mapping[str, Any]) -> int: """Determine the server type from a hello response.""" @@ -117,7 +120,7 @@ def tags(self) -> Mapping[str, Any]: return self._doc.get("tags", {}) @property - def primary(self) -> Optional[tuple[str, int]]: + def primary(self) -> tuple[str, int] | None: """This server's opinion about who the primary is, or None.""" if self._doc.get("primary"): return common.partition_node(self._doc["primary"]) @@ -125,7 +128,7 @@ def primary(self) -> Optional[tuple[str, int]]: return None @property - def replica_set_name(self) -> Optional[str]: + def replica_set_name(self) -> str | None: """Replica set name or None.""" return self._doc.get("setName") @@ -150,19 +153,19 @@ def max_wire_version(self) -> int: return self._doc.get("maxWireVersion", common.MAX_WIRE_VERSION) @property - def set_version(self) -> Optional[int]: + def set_version(self) -> int | None: return self._doc.get("setVersion") @property - def election_id(self) -> Optional[ObjectId]: + def election_id(self) -> ObjectId | None: return self._doc.get("electionId") @property - def cluster_time(self) -> Optional[ClusterTime]: + def cluster_time(self) -> ClusterTime | None: return self._doc.get("$clusterTime") @property - def logical_session_timeout_minutes(self) -> Optional[int]: + def logical_session_timeout_minutes(self) -> int | None: return self._doc.get("logicalSessionTimeoutMinutes") @property @@ -174,18 +177,18 @@ def is_readable(self) -> bool: return self._is_readable @property - def me(self) -> Optional[tuple[str, int]]: + def me(self) -> tuple[str, int] | None: me = self._doc.get("me") if me: return common.clean_node(me) return None @property - def last_write_date(self) -> Optional[datetime.datetime]: + def last_write_date(self) -> datetime.datetime | None: return self._doc.get("lastWrite", {}).get("lastWriteDate") @property - def compressors(self) -> Optional[list[str]]: + def compressors(self) -> list[str] | None: return self._doc.get("compression") @property @@ -201,12 +204,12 @@ def sasl_supported_mechs(self) -> list[str]: return self._doc.get("saslSupportedMechs", []) @property - def speculative_authenticate(self) -> Optional[Mapping[str, Any]]: + def speculative_authenticate(self) -> Mapping[str, Any] | None: """The speculativeAuthenticate field.""" return self._doc.get("speculativeAuthenticate") @property - def topology_version(self) -> Optional[Mapping[str, Any]]: + def topology_version(self) -> Mapping[str, Any] | None: return self._doc.get("topologyVersion") @property @@ -214,7 +217,7 @@ def awaitable(self) -> bool: return self._awaitable @property - def service_id(self) -> Optional[ObjectId]: + def service_id(self) -> ObjectId | None: return self._doc.get("serviceId") @property @@ -222,5 +225,5 @@ def hello_ok(self) -> bool: return self._doc.get("helloOk", False) @property - def connection_id(self) -> Optional[int]: + def connection_id(self) -> int | None: return self._doc.get("connectionId") diff --git a/pymongo/helpers_shared.py b/pymongo/helpers_shared.py index 15792972ac..594f55fb26 100644 --- a/pymongo/helpers_shared.py +++ b/pymongo/helpers_shared.py @@ -21,13 +21,10 @@ import time import traceback from collections import abc -from collections.abc import Container, Iterable, Mapping, Sequence from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, ) from pymongo import ASCENDING @@ -45,6 +42,8 @@ from pymongo.hello import HelloCompat if TYPE_CHECKING: + from collections.abc import Container, Iterable, Mapping, Sequence + from pymongo.cursor_shared import _Hint from pymongo.operations import _IndexList from pymongo.pool_options import PoolOptions @@ -128,7 +127,7 @@ class _RetryPolicy: def __init__( self, - attempts: Optional[int] = None, + attempts: int | None = None, backoff_initial: float = _BACKOFF_INITIAL, backoff_max: float = _BACKOFF_MAX, ): @@ -139,7 +138,7 @@ def __init__( self.backoff_initial = backoff_initial self.backoff_max = backoff_max - def backoff(self, attempt: int, base_backoff: Optional[float] = None) -> float: + def backoff(self, attempt: int, base_backoff: float | None = None) -> float: """Return the actual backoff duration for the given attempt and base backoff.""" return _backoff( max(0, attempt), @@ -177,7 +176,7 @@ def _get_timeout_details(options: PoolOptions) -> dict[str, float]: return details -def format_timeout_details(details: Optional[dict[str, float]]) -> str: +def format_timeout_details(details: dict[str, float] | None) -> str: result = "" if details: result += " (configured timeouts:" @@ -195,8 +194,8 @@ def _gen_index_name(keys: _IndexList) -> str: def _index_list( - key_or_list: _Hint, direction: Optional[Union[int, str]] = None -) -> Sequence[tuple[str, Union[int, str, Mapping[str, Any]]]]: + key_or_list: _Hint, direction: int | str | None = None +) -> Sequence[tuple[str, int | str | Mapping[str, Any]]]: """Helper to generate a list of (key, direction) pairs. Takes such a list, or a single key, or a single key and direction. @@ -266,10 +265,10 @@ def _validate_index_key_pair(key: Any, value: Any) -> None: def _check_command_response( response: _DocumentOut, - max_wire_version: Optional[int], - allowable_errors: Optional[Container[Union[int, str]]] = None, + max_wire_version: int | None, + allowable_errors: Container[int | str] | None = None, parse_write_concern_error: bool = False, - pool_opts: Optional[PoolOptions] = None, + pool_opts: PoolOptions | None = None, ) -> None: """Check the response to a command for errors.""" if "ok" not in response: @@ -343,7 +342,7 @@ def _raise_write_concern_error(error: Any) -> NoReturn: raise WriteConcernError(error.get("errmsg"), error.get("code"), error) -def _get_wce_doc(result: Mapping[str, Any]) -> Optional[Mapping[str, Any]]: +def _get_wce_doc(result: Mapping[str, Any]) -> Mapping[str, Any] | None: """Return the writeConcernError or None.""" wce = result.get("writeConcernError") if wce: @@ -370,7 +369,7 @@ def _check_write_command_response(result: Mapping[str, Any]) -> None: def _fields_list_to_dict( - fields: Union[Mapping[str, Any], Iterable[str]], option_name: str + fields: Mapping[str, Any] | Iterable[str], option_name: str ) -> Mapping[str, Any]: """Takes a sequence of field names and returns a matching dictionary. diff --git a/pymongo/lock.py b/pymongo/lock.py index ad990fce3f..9f844bf8e3 100644 --- a/pymongo/lock.py +++ b/pymongo/lock.py @@ -22,7 +22,7 @@ import threading import weakref from asyncio import wait_for -from typing import Any, Optional, TypeVar +from typing import Any import pymongo._asyncio_lock @@ -31,8 +31,6 @@ # References to instances of _create_lock _forkable_locks: weakref.WeakSet[threading.Lock] = weakref.WeakSet() -_T = TypeVar("_T") - # Needed to support 3.13 asyncio fixes (https://github.com/python/cpython/issues/112202) # in older versions of Python if sys.version_info >= (3, 13): @@ -59,7 +57,7 @@ def _async_create_lock() -> Lock: def _create_condition( - lock: threading.Lock, condition_class: Optional[Any] = None + lock: threading.Lock, condition_class: Any | None = None ) -> threading.Condition: """Represents a threading.Condition.""" if condition_class: @@ -67,7 +65,7 @@ def _create_condition( return threading.Condition(lock) -def _async_create_condition(lock: Lock, condition_class: Optional[Any] = None) -> Condition: +def _async_create_condition(lock: Lock, condition_class: Any | None = None) -> Condition: """Represents an asyncio.Condition.""" if condition_class: return condition_class(lock) @@ -81,12 +79,12 @@ def _release_locks() -> None: lock.release() -async def _async_cond_wait(condition: Condition, timeout: Optional[float]) -> bool: +async def _async_cond_wait(condition: Condition, timeout: float | None) -> bool: try: return await wait_for(condition.wait(), timeout) - except asyncio.TimeoutError: + except TimeoutError: return False -def _cond_wait(condition: threading.Condition, timeout: Optional[float]) -> bool: +def _cond_wait(condition: threading.Condition, timeout: float | None) -> bool: return condition.wait(timeout) diff --git a/pymongo/message.py b/pymongo/message.py index 32fd83d636..18c4ae162a 100644 --- a/pymongo/message.py +++ b/pymongo/message.py @@ -24,14 +24,12 @@ import random import struct -from collections.abc import Callable, Iterable, Mapping, MutableMapping from io import BytesIO as _BytesIO from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, + Self, ) import bson @@ -43,7 +41,6 @@ _inflate_bson, ) from pymongo.common import MONGOS_EXHAUST_WIRE_VERSION -from pymongo.monitoring import _EventListeners try: from pymongo import _cmessage # type: ignore[attr-defined] @@ -59,7 +56,10 @@ from pymongo.read_preferences import ReadPreference, _ServerMode if TYPE_CHECKING: + from collections.abc import Callable, Iterable, Mapping, MutableMapping + from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext + from pymongo.monitoring import _EventListeners from pymongo.read_concern import ReadConcern from pymongo.typings import ( _Address, @@ -170,15 +170,15 @@ def _convert_client_bulk_exception(exception: Exception) -> dict[str, Any]: def _gen_find_command( coll: str, spec: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]], + projection: Mapping[str, Any] | Iterable[str] | None, skip: int, limit: int, - batch_size: Optional[int], - options: Optional[int], + batch_size: int | None, + options: int | None, read_concern: ReadConcern, - collation: Optional[Mapping[str, Any]] = None, - session: Optional[_AgnosticClientSession] = None, - allow_disk_use: Optional[bool] = None, + collation: Mapping[str, Any] | None = None, + session: _AgnosticClientSession | None = None, + allow_disk_use: bool | None = None, ) -> dict[str, Any]: """Generate a find command document.""" cmd: dict[str, Any] = {"find": coll} @@ -223,11 +223,11 @@ def _gen_find_command( def _gen_get_more_command( - cursor_id: Optional[int], + cursor_id: int | None, coll: str, - batch_size: Optional[int], - max_await_time_ms: Optional[int], - comment: Optional[Any], + batch_size: int | None, + max_await_time_ms: int | None, + comment: Any | None, ) -> dict[str, Any]: """Generate a getMore command document.""" cmd: dict[str, Any] = {"getMore": cursor_id, "collection": coll} @@ -245,7 +245,7 @@ def _gen_get_more_command( def _compress( - operation: int, data: bytes, ctx: Union[SnappyContext, ZlibContext, ZstdContext] + operation: int, data: bytes, ctx: SnappyContext | ZlibContext | ZstdContext ) -> tuple[int, bytes]: """Takes message data, compresses it, and adds an OP_COMPRESSED header.""" compressed = ctx.compress(data) @@ -285,7 +285,7 @@ def _op_msg_no_header( flags: int, command: Mapping[str, Any], identifier: str, - docs: Optional[list[Mapping[str, Any]]], + docs: list[Mapping[str, Any]] | None, opts: CodecOptions[Any], ) -> tuple[bytes, int, int]: """Get a OP_MSG message. @@ -317,9 +317,9 @@ def _op_msg_compressed( flags: int, command: Mapping[str, Any], identifier: str, - docs: Optional[list[Mapping[str, Any]]], + docs: list[Mapping[str, Any]] | None, opts: CodecOptions[Any], - ctx: Union[SnappyContext, ZlibContext, ZstdContext], + ctx: SnappyContext | ZlibContext | ZstdContext, ) -> tuple[int, bytes, int, int]: """Internal OP_MSG message helper.""" msg, total_size, max_bson_size = _op_msg_no_header(flags, command, identifier, docs, opts) @@ -331,7 +331,7 @@ def _op_msg_uncompressed( flags: int, command: Mapping[str, Any], identifier: str, - docs: Optional[list[Mapping[str, Any]]], + docs: list[Mapping[str, Any]] | None, opts: CodecOptions[Any], ) -> tuple[int, bytes, int, int]: """Internal compressed OP_MSG message helper.""" @@ -348,9 +348,9 @@ def _op_msg( flags: int, command: MutableMapping[str, Any], dbname: str, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, opts: CodecOptions[Any], - ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None, + ctx: SnappyContext | ZlibContext | ZstdContext | None = None, ) -> tuple[int, bytes, int, int]: """Get a OP_MSG message.""" command["$db"] = dbname @@ -407,9 +407,9 @@ def __init__( database_name: str, cmd_name: str, conn: _AgnosticConnection, - operation_id: Optional[int], + operation_id: int | None, listeners: _EventListeners, - session: Optional[_AgnosticClientSession], + session: _AgnosticClientSession | None, op_type: int, codec: CodecOptions[Any], ): @@ -458,9 +458,9 @@ def __init__( database_name: str, cmd_name: str, conn: _AgnosticConnection, - operation_id: Optional[int], + operation_id: int | None, listeners: _EventListeners, - session: Optional[_AgnosticClientSession], + session: _AgnosticClientSession | None, op_type: int, codec: CodecOptions[Any], ): @@ -477,7 +477,7 @@ def __init__( def batch_command( self, cmd: MutableMapping[str, Any], docs: list[Mapping[str, Any]] - ) -> tuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]]]: + ) -> tuple[int, bytes | dict[str, Any], list[Mapping[str, Any]]]: namespace = self.db_name + ".$cmd" request_id, msg, to_send = _do_batched_op_msg( namespace, self.op_type, cmd, docs, self.codec, self @@ -701,9 +701,9 @@ def __init__( database_name: str, cmd_name: str, conn: _AgnosticConnection, - operation_id: Optional[int], + operation_id: int | None, listeners: _EventListeners, - session: Optional[_AgnosticClientSession], + session: _AgnosticClientSession | None, codec: CodecOptions[Any], ): super().__init__( @@ -722,7 +722,7 @@ def batch_command( cmd: MutableMapping[str, Any], operations: list[tuple[str, Mapping[str, Any]]], namespaces: list[str], - ) -> tuple[int, Union[bytes, dict[str, Any]], list[Mapping[str, Any]], list[Mapping[str, Any]]]: + ) -> tuple[int, bytes | dict[str, Any], list[Mapping[str, Any]], list[Mapping[str, Any]]]: request_id, msg, to_send_ops, to_send_ns = _client_do_batched_op_msg( cmd, operations, namespaces, self.codec, self ) @@ -756,8 +756,7 @@ def _client_construct_op_msg( buf.write(b"\x00\x00\x00\x00") buf.write(b"ops\x00") # Write all the ops documents - for op_encoded in to_send_ops_encoded: - buf.write(op_encoded) + buf.writelines(to_send_ops_encoded) resume_location = buf.tell() # Write type 1 section size length = buf.tell() @@ -772,8 +771,7 @@ def _client_construct_op_msg( buf.write(b"\x00\x00\x00\x00") buf.write(b"nsInfo\x00") # Write all the nsInfo documents - for ns_encoded in to_send_ns_encoded: - buf.write(ns_encoded) + buf.writelines(to_send_ns_encoded) # Write type 1 section size length = buf.tell() buf.seek(size_location) @@ -833,7 +831,9 @@ def _check_doc_size_limits( total_ops_length = 0 total_ns_length = 0 - for idx, ((real_op_type, op_doc), namespace) in enumerate(zip(operations, namespaces)): + for idx, ((real_op_type, op_doc), namespace) in enumerate( + zip(operations, namespaces, strict=True) + ): op_type = real_op_type # Check insert/replace document size if unacknowledged. if real_op_type == "insert": @@ -1100,8 +1100,8 @@ def __init__(self, flags: int, payload_document: bytes | memoryview): def raw_response( self, - cursor_id: Optional[int] = None, - user_fields: Optional[Mapping[str, Any]] = {}, + cursor_id: int | None = None, + user_fields: Mapping[str, Any] | None = {}, ) -> list[Mapping[str, Any]]: """ cursor_id is ignored @@ -1114,9 +1114,9 @@ def raw_response( def unpack_response( self, - cursor_id: Optional[int] = None, + cursor_id: int | None = None, codec_options: CodecOptions[Any] = _UNICODE_REPLACE_CODEC_OPTIONS, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> list[dict[str, Any]]: """Unpack a OP_MSG command response. @@ -1216,16 +1216,16 @@ def __init__( coll: str, ntoskip: int, spec: Mapping[str, Any], - fields: Optional[Mapping[str, Any]], + fields: Mapping[str, Any] | None, codec_options: CodecOptions[Any], read_preference: _ServerMode, limit: int, batch_size: int, read_concern: ReadConcern, - collation: Optional[Mapping[str, Any]], - session: Optional[_AgnosticClientSession], + collation: Mapping[str, Any] | None, + session: _AgnosticClientSession | None, client: _AgnosticMongoClient, - allow_disk_use: Optional[bool], + allow_disk_use: bool | None, exhaust: bool, ): self.flags = flags @@ -1244,7 +1244,7 @@ def __init__( self.client = client self.allow_disk_use = allow_disk_use self.name = "find" - self._as_command: Optional[tuple[dict[str, Any], str]] = None + self._as_command: tuple[dict[str, Any], str] | None = None self.exhaust = exhaust def reset(self) -> None: @@ -1350,9 +1350,9 @@ def __init__( cursor_id: int, codec_options: CodecOptions[Any], read_preference: _ServerMode, - session: Optional[_AgnosticClientSession], + session: _AgnosticClientSession | None, client: _AgnosticMongoClient, - max_await_time_ms: Optional[int], + max_await_time_ms: int | None, conn_mgr: Any, exhaust: bool, comment: Any, @@ -1367,7 +1367,7 @@ def __init__( self.client = client self.max_await_time_ms = max_await_time_ms self.conn_mgr = conn_mgr - self._as_command: Optional[tuple[dict[str, Any], str]] = None + self._as_command: tuple[dict[str, Any], str] | None = None self.exhaust = exhaust self.comment = comment @@ -1435,7 +1435,7 @@ class _CursorAddress(tuple[Any, ...]): __namespace: Any - def __new__(cls, address: _Address, namespace: str) -> _CursorAddress: + def __new__(cls, address: _Address, namespace: str) -> Self: self = tuple.__new__(cls, address) self.__namespace = namespace return self diff --git a/pymongo/mongo_client_shared.py b/pymongo/mongo_client_shared.py index f2f8629a1c..f0578f2de0 100644 --- a/pymongo/mongo_client_shared.py +++ b/pymongo/mongo_client_shared.py @@ -17,7 +17,7 @@ from __future__ import annotations from collections.abc import Callable, Mapping -from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar, Union, cast +from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none, log_command_retry @@ -54,7 +54,7 @@ _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) -def _retryable_error_doc(exc: PyMongoError) -> Optional[Mapping[str, Any]]: +def _retryable_error_doc(exc: PyMongoError) -> Mapping[str, Any] | None: """Return the server response from PyMongo exception or None.""" if isinstance(exc, (BulkWriteError, ClientBulkWriteException)): # Check the last writeConcernError to determine if this @@ -62,7 +62,7 @@ def _retryable_error_doc(exc: PyMongoError) -> Optional[Mapping[str, Any]]: wces = exc.details["writeConcernErrors"] return wces[-1] if wces else None if isinstance(exc, (NotPrimaryError, OperationFailure)): - return cast(Mapping[str, Any], exc.details) + return cast("Mapping[str, Any]", exc.details) return None @@ -101,7 +101,7 @@ def _after_fork_child(clients: Mapping[Any, Any]) -> None: _release_locks() # Perform cleanup in clients (i.e. get rid of topology) - for _, client in clients.items(): + for client in clients.values(): client._after_fork() @@ -140,6 +140,7 @@ class _AgnosticClientConnectionRetryableBase(Generic[T, _ServerT, _FuncT]): "_base_backoff_ms", "_bulk", "_client", + "_conn_mgr", "_deprioritized_servers", "_func", "_is_aggregate_write", @@ -162,18 +163,19 @@ def __init__( self, mongo_client: _AgnosticMongoClient, func: _FuncT, - bulk: Optional[Union[_AgnosticBulk, _AgnosticClientBulk]], + bulk: _AgnosticBulk | _AgnosticClientBulk | None, operation: str, is_read: bool = False, - session: Optional[_AgnosticClientSession] = None, - read_pref: Optional[_ServerMode] = None, - address: Optional[_Address] = None, + session: _AgnosticClientSession | None = None, + read_pref: _ServerMode | None = None, + address: _Address | None = None, retryable: bool = False, - operation_id: Optional[int] = None, + operation_id: int | None = None, is_run_command: bool = False, is_aggregate_write: bool = False, + conn_mgr: Any = None, ): - self._last_error: Optional[Exception] = None + self._last_error: Exception | None = None self._retrying = False self._always_retryable = False self._max_retries = float("inf") if _csot.get_timeout() is not None else 1 @@ -190,7 +192,7 @@ def __init__( ) self._address = address self._server: _ServerT = None # type: ignore - self._deprioritized_servers: Optional[list[_ServerT]] = None + self._deprioritized_servers: list[_ServerT] | None = None self._operation = operation # Only generate an operation id when APM/logging is enabled. if operation_id is None: @@ -199,7 +201,8 @@ def __init__( self._attempt_number = 0 self._is_run_command = is_run_command self._is_aggregate_write = is_aggregate_write - self._base_backoff_ms: Optional[float] = None + self._base_backoff_ms: float | None = None + self._conn_mgr = conn_mgr def _is_not_eligible_for_retry(self) -> bool: """Checks if the exchange is not eligible for retry""" diff --git a/pymongo/monitoring.py b/pymongo/monitoring.py index 252b0daef0..52a63b7cd8 100644 --- a/pymongo/monitoring.py +++ b/pymongo/monitoring.py @@ -188,21 +188,21 @@ def connection_checked_in(self, event): from __future__ import annotations -import datetime from collections import abc, namedtuple -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any -from bson.objectid import ObjectId from pymongo.hello import Hello, HelloCompat from pymongo.helpers_shared import _SENSITIVE_COMMANDS, _handle_exception -from pymongo.typings import _Address, _DocumentOut if TYPE_CHECKING: + import datetime + from collections.abc import Mapping, Sequence from datetime import timedelta + from bson.objectid import ObjectId from pymongo.server_description import ServerDescription from pymongo.topology_description import TopologyDescription + from pymongo.typings import _Address, _DocumentOut _Listeners = namedtuple( @@ -541,10 +541,10 @@ def __init__( command_name: str, request_id: int, connection_id: _Address, - operation_id: Optional[int], - service_id: Optional[ObjectId] = None, + operation_id: int | None, + service_id: ObjectId | None = None, database_name: str = "", - server_connection_id: Optional[int] = None, + server_connection_id: int | None = None, ) -> None: self.__cmd_name = command_name self.__rqst_id = request_id @@ -570,7 +570,7 @@ def connection_id(self) -> _Address: return self.__conn_id @property - def service_id(self) -> Optional[ObjectId]: + def service_id(self) -> ObjectId | None: """The service_id this command was sent to, or ``None``. .. versionadded:: 3.12 @@ -578,7 +578,7 @@ def service_id(self) -> Optional[ObjectId]: return self.__service_id @property - def operation_id(self) -> Optional[int]: + def operation_id(self) -> int | None: """An id for this series of events or None.""" return self.__op_id @@ -591,7 +591,7 @@ def database_name(self) -> str: return self.__db @property - def server_connection_id(self) -> Optional[int]: + def server_connection_id(self) -> int | None: """The server-side connection id for the connection this command was sent on, or ``None``. .. versionadded:: 4.7 @@ -619,9 +619,9 @@ def __init__( database_name: str, request_id: int, connection_id: _Address, - operation_id: Optional[int], - service_id: Optional[ObjectId] = None, - server_connection_id: Optional[int] = None, + operation_id: int | None, + service_id: ObjectId | None = None, + server_connection_id: int | None = None, ) -> None: if not command: raise ValueError(f"{command!r} is not a valid command") @@ -679,10 +679,10 @@ def __init__( command_name: str, request_id: int, connection_id: _Address, - operation_id: Optional[int], - service_id: Optional[ObjectId] = None, + operation_id: int | None, + service_id: ObjectId | None = None, database_name: str = "", - server_connection_id: Optional[int] = None, + server_connection_id: int | None = None, ) -> None: super().__init__( command_name, @@ -737,10 +737,10 @@ def __init__( command_name: str, request_id: int, connection_id: _Address, - operation_id: Optional[int], - service_id: Optional[ObjectId] = None, + operation_id: int | None, + service_id: ObjectId | None = None, database_name: str = "", - server_connection_id: Optional[int] = None, + server_connection_id: int | None = None, ) -> None: super().__init__( command_name, @@ -842,7 +842,7 @@ class PoolClearedEvent(_PoolEvent): def __init__( self, address: _Address, - service_id: Optional[ObjectId] = None, + service_id: ObjectId | None = None, interrupt_connections: bool = False, ) -> None: super().__init__(address) @@ -850,7 +850,7 @@ def __init__( self.__interrupt_connections = interrupt_connections @property - def service_id(self) -> Optional[ObjectId]: + def service_id(self) -> ObjectId | None: """Connections with this service_id are cleared. When service_id is ``None``, all connections in the pool are cleared. @@ -965,12 +965,12 @@ class _ConnectionDurationEvent(_ConnectionIdEvent): __slots__ = ("__duration",) - def __init__(self, address: _Address, connection_id: int, duration: Optional[float]) -> None: + def __init__(self, address: _Address, connection_id: int, duration: float | None) -> None: super().__init__(address, connection_id) self.__duration = duration @property - def duration(self) -> Optional[float]: + def duration(self) -> float | None: """The duration of the connection event. .. versionadded:: 4.7 @@ -1064,7 +1064,7 @@ class ConnectionCheckOutFailedEvent(_ConnectionDurationEvent): __slots__ = ("__reason",) - def __init__(self, address: _Address, reason: str, duration: Optional[float]) -> None: + def __init__(self, address: _Address, reason: str, duration: float | None) -> None: super().__init__(address=address, connection_id=0, duration=duration) self.__reason = reason @@ -1387,7 +1387,7 @@ class _EventListeners: :param listeners: A list of event listeners. """ - def __init__(self, listeners: Optional[Sequence[_EventListener]]): + def __init__(self, listeners: Sequence[_EventListener] | None): self.__command_listeners = _LISTENERS.command_listeners[:] self.__server_listeners = _LISTENERS.server_listeners[:] lst = _LISTENERS.server_heartbeat_listeners @@ -1453,9 +1453,9 @@ def publish_command_start( database_name: str, request_id: int, connection_id: _Address, - server_connection_id: Optional[int], - op_id: Optional[int] = None, - service_id: Optional[ObjectId] = None, + server_connection_id: int | None, + op_id: int | None = None, + service_id: ObjectId | None = None, ) -> None: """Publish a CommandStartedEvent to all command listeners. @@ -1492,9 +1492,9 @@ def publish_command_success( command_name: str, request_id: int, connection_id: _Address, - server_connection_id: Optional[int], - op_id: Optional[int] = None, - service_id: Optional[ObjectId] = None, + server_connection_id: int | None, + op_id: int | None = None, + service_id: ObjectId | None = None, speculative_hello: bool = False, database_name: str = "", ) -> None: @@ -1541,9 +1541,9 @@ def publish_command_failure( command_name: str, request_id: int, connection_id: _Address, - server_connection_id: Optional[int], - op_id: Optional[int] = None, - service_id: Optional[ObjectId] = None, + server_connection_id: int | None, + op_id: int | None = None, + service_id: ObjectId | None = None, database_name: str = "", ) -> None: """Publish a CommandFailedEvent to all command listeners. @@ -1749,7 +1749,7 @@ def publish_pool_ready(self, address: _Address) -> None: def publish_pool_cleared( self, address: _Address, - service_id: Optional[ObjectId], + service_id: ObjectId | None, interrupt_connections: bool = False, ) -> None: """Publish a :class:`PoolClearedEvent` to all pool listeners.""" diff --git a/pymongo/network_layer.py b/pymongo/network_layer.py index 5425a68503..f60e27738c 100644 --- a/pymongo/network_layer.py +++ b/pymongo/network_layer.py @@ -19,17 +19,13 @@ import asyncio import collections import errno -import socket import struct import sys import time from asyncio import AbstractEventLoop, BaseTransport, BufferedProtocol, Future, Transport -from collections.abc import Callable from typing import ( TYPE_CHECKING, Any, - Optional, - Union, ) from pymongo import _csot, ssl_support @@ -61,6 +57,9 @@ ) if TYPE_CHECKING: + import socket + from collections.abc import Callable + from pymongo.asynchronous.pool import AsyncConnection from pymongo.synchronous.pool import Connection @@ -73,7 +72,7 @@ # These socket-based I/O methods are for KMS requests and any other network operations that do not use # the MongoDB wire protocol -async def async_socket_sendall(sock: Union[socket.socket, _sslConn], buf: bytes) -> None: +async def async_socket_sendall(sock: socket.socket | _sslConn, buf: bytes) -> None: timeout = sock.gettimeout() loop = asyncio.get_running_loop() try: @@ -87,15 +86,15 @@ async def async_socket_sendall(sock: Union[socket.socket, _sslConn], buf: bytes) await asyncio.wait_for(loop.sock_sendall(sock, buf), timeout=timeout) # type: ignore[arg-type] finally: sock.settimeout(timeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc if sys.platform != "win32": async def _async_socket_receive_ssl( - conn: _sslConn, length: int, loop: AbstractEventLoop, once: Optional[bool] = False + conn: _sslConn, length: int, loop: AbstractEventLoop, once: bool | None = False ) -> memoryview: mv = memoryview(bytearray(length)) total_read = 0 @@ -148,7 +147,7 @@ def _is_ready(fut: Future[Any]) -> None: # The default Windows asyncio event loop does not support loop.add_reader/add_writer: # https://docs.python.org/3/library/asyncio-platforms.html#asyncio-platform-support async def _async_socket_receive_ssl( - conn: _sslConn, length: int, dummy: AbstractEventLoop, once: Optional[bool] = False + conn: _sslConn, length: int, dummy: AbstractEventLoop, once: bool | None = False ) -> memoryview: mv = memoryview(bytearray(length)) total_read = 0 @@ -184,7 +183,7 @@ async def _async_blocking_socket_call( loop: AbstractEventLoop, func: Callable[..., Any], arg: Any, - timeout: Optional[float], + timeout: float | None, ) -> Any: """Run a blocking socket operation in a worker thread with a timeout. @@ -195,7 +194,7 @@ async def _async_blocking_socket_call( fut = asyncio.shield(inner) try: return await asyncio.wait_for(fut, timeout=timeout) - except (asyncio.CancelledError, asyncio.TimeoutError): + except (asyncio.CancelledError, TimeoutError): # Wait for the worker, shielded from further cancellations, so the # caller does not close the socket under it. while True: @@ -213,7 +212,7 @@ async def _async_blocking_socket_call( raise OSError("connection closed") from exc -def sendall(sock: Union[socket.socket, _sslConn], buf: bytes) -> None: +def sendall(sock: socket.socket | _sslConn, buf: bytes) -> None: """Send all of buf on the socket.""" sock.sendall(buf) @@ -227,9 +226,7 @@ async def _poll_cancellation(conn: AsyncConnection) -> None: await asyncio.sleep(_POLL_TIMEOUT) -async def async_receive_data_socket( - sock: Union[socket.socket, _sslConn], length: int -) -> memoryview: +async def async_receive_data_socket(sock: socket.socket | _sslConn, length: int) -> memoryview: """Receive exactly length bytes from the socket.""" timeout = sock.gettimeout() sock.settimeout(0.0) @@ -245,8 +242,9 @@ async def async_receive_data_socket( _async_socket_receive(sock, length, loop), # type: ignore[arg-type] timeout=timeout, ) - except asyncio.TimeoutError as err: - raise socket.timeout("timed out") from err + except TimeoutError as err: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from err finally: sock.settimeout(timeout) @@ -268,7 +266,7 @@ async def _async_socket_receive( _WINDOWS = sys.platform == "win32" -def wait_for_read(conn: Connection, deadline: Optional[float]) -> None: +def wait_for_read(conn: Connection, deadline: float | None) -> None: """Block until at least one byte is read, or a timeout, or a cancel.""" sock = conn.conn.sock timed_out = False @@ -298,10 +296,10 @@ def wait_for_read(conn: Connection, deadline: Optional[float]) -> None: if readable: return if timed_out: - raise socket.timeout("timed out") + raise TimeoutError("timed out") -def receive_data(conn: Connection, length: int, deadline: Optional[float]) -> memoryview: +def receive_data(conn: Connection, length: int, deadline: float | None) -> memoryview: buf = bytearray(length) mv = memoryview(buf) bytes_read = 0 @@ -333,8 +331,8 @@ def receive_data(conn: Connection, length: int, deadline: Optional[float]) -> me if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None # We reached the true deadline. - raise socket.timeout("timed out") from None - except socket.timeout: + raise TimeoutError("timed out") from None + except TimeoutError: if conn.cancel_context.cancelled: raise _OperationCancelled("operation cancelled") from None if _WINDOWS or ( @@ -413,7 +411,7 @@ def sock(self) -> socket.socket: class NetworkingInterface(NetworkingInterfaceBase): - def __init__(self, conn: Union[socket.socket, _sslConn]): + def __init__(self, conn: socket.socket | _sslConn): super().__init__(conn) def gettimeout(self) -> float | None: @@ -429,11 +427,11 @@ def is_closing(self) -> bool: return self.conn.is_closing() @property - def get_conn(self) -> Union[socket.socket, _sslConn]: + def get_conn(self) -> socket.socket | _sslConn: return self.conn @property - def sock(self) -> Union[socket.socket, _sslConn]: + def sock(self) -> socket.socket | _sslConn: return self.conn def fileno(self) -> int: @@ -444,7 +442,7 @@ def recv_into(self, buffer: bytes | memoryview) -> int: class PyMongoProtocol(BufferedProtocol): - def __init__(self, timeout: Optional[float] = None): + def __init__(self, timeout: float | None = None): self.transport: Transport = None # type: ignore[assignment] # Each message is reader in 2-3 parts: header, compression header, and message body # The message buffer is allocated after the header is read. @@ -452,7 +450,7 @@ def __init__(self, timeout: Optional[float] = None): self._header_index = 0 self._compression_header = memoryview(bytearray(9)) self._compression_index = 0 - self._message: Optional[memoryview] = None + self._message: memoryview | None = None self._message_index = 0 # State. TODO: replace booleans with an enum? self._expecting_header = True @@ -460,12 +458,12 @@ def __init__(self, timeout: Optional[float] = None): self._message_size = 0 self._op_code = 0 self._connection_lost = False - self._read_waiter: Optional[Future[Any]] = None + self._read_waiter: Future[Any] | None = None self._timeout = timeout self._is_compressed = False - self._compressor_id: Optional[int] = None + self._compressor_id: int | None = None self._max_message_size = MAX_MESSAGE_SIZE - self._response_to: Optional[int] = None + self._response_to: int | None = None self._closed = asyncio.get_running_loop().create_future() self._pending_messages: collections.deque[Future[Any]] = collections.deque() self._done_messages: collections.deque[Future[Any]] = collections.deque() @@ -492,7 +490,7 @@ async def write(self, message: bytes) -> None: self.transport.write(message) self.transport.resume_reading() - async def read(self, request_id: Optional[int], max_message_size: int) -> tuple[bytes, int]: + async def read(self, request_id: int | None, max_message_size: int) -> tuple[bytes, int]: """Read a single MongoDB Wire Protocol message from this connection.""" if self.transport: try: @@ -649,7 +647,7 @@ def process_compression_header(self) -> tuple[int, int, int]: ) return op_code, uncompressed_size, compressor_id - def _resolve_pending_messages(self, exc: Optional[Exception] = None) -> None: + def _resolve_pending_messages(self, exc: Exception | None = None) -> None: pending = list(self._pending_messages) for msg in pending: if not msg.done(): @@ -659,12 +657,12 @@ def _resolve_pending_messages(self, exc: Optional[Exception] = None) -> None: msg.set_exception(exc) self._done_messages.append(msg) - def close(self, exc: Optional[Exception] = None) -> None: + def close(self, exc: Exception | None = None) -> None: self.transport.abort() self._resolve_pending_messages(exc) self._connection_lost = True - def connection_lost(self, exc: Optional[Exception] = None) -> None: + def connection_lost(self, exc: Exception | None = None) -> None: self._resolve_pending_messages(exc) if not self._closed.done(): self._closed.set_result(None) @@ -676,18 +674,18 @@ async def wait_closed(self) -> None: async def async_sendall(conn: PyMongoProtocol, buf: bytes) -> None: try: await asyncio.wait_for(conn.write(buf), timeout=conn.gettimeout) - except asyncio.TimeoutError as exc: - # Convert the asyncio.wait_for timeout error to socket.timeout which pool.py understands. - raise socket.timeout("timed out") from exc + except TimeoutError as exc: + # asyncio.wait_for raises TimeoutError without a message. + raise TimeoutError("timed out") from exc async def async_receive_message( conn: AsyncConnection, - request_id: Optional[int], + request_id: int | None, max_message_size: int = MAX_MESSAGE_SIZE, ) -> _OpMsg: """Receive a raw BSON message or raise socket.error.""" - timeout: Optional[Union[float, int]] + timeout: float | int | None timeout = conn.conn.gettimeout if _csot.get_timeout(): deadline = _csot.get_deadline() @@ -714,7 +712,7 @@ async def async_receive_message( if pending: await asyncio.wait(pending) if len(done) == 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") if read_task in done: data, op_code = read_task.result() try: @@ -733,7 +731,7 @@ async def async_receive_message( def receive_message( - conn: Connection, request_id: Optional[int], max_message_size: int = MAX_MESSAGE_SIZE + conn: Connection, request_id: int | None, max_message_size: int = MAX_MESSAGE_SIZE ) -> _OpMsg: """Receive a raw BSON message or raise socket.error.""" if _csot.get_timeout(): diff --git a/pymongo/ocsp_cache.py b/pymongo/ocsp_cache.py index 2df232848f..afa0c50ea9 100644 --- a/pymongo/ocsp_cache.py +++ b/pymongo/ocsp_cache.py @@ -19,7 +19,7 @@ from collections import namedtuple from datetime import datetime as _datetime from datetime import timezone -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from pymongo.lock import _create_lock @@ -27,7 +27,7 @@ from cryptography.x509.ocsp import OCSPRequest, OCSPResponse -def _next_update(value: OCSPResponse) -> Optional[_datetime]: +def _next_update(value: OCSPResponse) -> _datetime | None: """Compat helper to return the response's next_update_utc.""" # Added in cryptography 43.0.0. if hasattr(value, "next_update_utc"): @@ -35,7 +35,7 @@ def _next_update(value: OCSPResponse) -> Optional[_datetime]: return value.next_update -def _this_update(value: OCSPResponse) -> Optional[_datetime]: +def _this_update(value: OCSPResponse) -> _datetime | None: """Compat helper to return the response's this_update_utc.""" # Added in cryptography 43.0.0. if hasattr(value, "this_update_utc"): diff --git a/pymongo/ocsp_support.py b/pymongo/ocsp_support.py index 7990c953b4..9c7f3ecab8 100644 --- a/pymongo/ocsp_support.py +++ b/pymongo/ocsp_support.py @@ -18,10 +18,9 @@ import logging as _logging import re as _re -from collections.abc import Iterable from datetime import datetime as _datetime from datetime import timezone -from typing import TYPE_CHECKING, Optional, Union +from typing import TYPE_CHECKING from cryptography.exceptions import InvalidSignature as _InvalidSignature from cryptography.hazmat.backends import default_backend as _default_backend @@ -68,6 +67,8 @@ from pymongo.ocsp_cache import _next_update, _this_update if TYPE_CHECKING: + from collections.abc import Iterable + from cryptography.hazmat.primitives.asymmetric import ( dsa, ec, @@ -92,20 +93,20 @@ # Must stay in step with cryptography's CertificatePublicKeyTypes, the # return type of Certificate.public_key(). cryptography does not export a # public alias for it, so it is spelled out here. - CertificateIssuerPublicKeyTypes = Union[ - dsa.DSAPublicKey, - rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey, - mldsa.MLDSA44PublicKey, - mldsa.MLDSA65PublicKey, - mldsa.MLDSA87PublicKey, - mlkem.MLKEM768PublicKey, - mlkem.MLKEM1024PublicKey, - x25519.X25519PublicKey, - x448.X448PublicKey, - ] + CertificateIssuerPublicKeyTypes = ( + dsa.DSAPublicKey + | rsa.RSAPublicKey + | ec.EllipticCurvePublicKey + | ed25519.Ed25519PublicKey + | ed448.Ed448PublicKey + | mldsa.MLDSA44PublicKey + | mldsa.MLDSA65PublicKey + | mldsa.MLDSA87PublicKey + | mlkem.MLKEM768PublicKey + | mlkem.MLKEM1024PublicKey + | x25519.X25519PublicKey + | x448.X448PublicKey + ) # Note: the functions in this module generally return 1 or 0. The reason # is simple. The entry point, ocsp_callback, is registered as a callback @@ -120,8 +121,8 @@ def _get_issuer_cert( - cert: Certificate, chain: Iterable[Certificate], trusted_ca_certs: Optional[list[Certificate]] -) -> Optional[Certificate]: + cert: Certificate, chain: Iterable[Certificate], trusted_ca_certs: list[Certificate] | None +) -> Certificate | None: issuer_name = cert.issuer for candidate in chain: if candidate.subject == issuer_name: @@ -141,7 +142,7 @@ def _get_issuer_cert( def _verify_signature( key: CertificateIssuerPublicKeyTypes, signature: bytes, - algorithm: Union[Prehashed, HashAlgorithm, None], + algorithm: Prehashed | HashAlgorithm | None, data: bytes, ) -> int: # See cryptography.x509.Certificate.public_key @@ -173,7 +174,7 @@ def _verify_signature( def _get_extension( cert: Certificate, klass: type[ExtensionTypeVar] -) -> Optional[Extension[ExtensionTypeVar]]: +) -> Extension[ExtensionTypeVar] | None: try: return cert.extensions.get_extension_for_class(klass) except _ExtensionNotFound: @@ -198,7 +199,7 @@ def _public_key_hash(cert: Certificate) -> bytes: def _get_certs_by_key_hash( - certificates: Iterable[Certificate], issuer: Certificate, responder_key_hash: Optional[bytes] + certificates: Iterable[Certificate], issuer: Certificate, responder_key_hash: bytes | None ) -> list[Certificate]: return [ cert @@ -208,7 +209,7 @@ def _get_certs_by_key_hash( def _get_certs_by_name( - certificates: Iterable[Certificate], issuer: Certificate, responder_name: Optional[Name] + certificates: Iterable[Certificate], issuer: Certificate, responder_name: Name | None ) -> list[Certificate]: return [ cert @@ -305,8 +306,8 @@ def _verify_response(issuer: Certificate, response: OCSPResponse) -> int: def _get_ocsp_response( - cert: Certificate, issuer: Certificate, uri: Union[str, bytes], ocsp_response_cache: _OCSPCache -) -> Optional[OCSPResponse]: + cert: Certificate, issuer: Certificate, uri: str | bytes, ocsp_response_cache: _OCSPCache +) -> OCSPResponse | None: ocsp_request = _build_ocsp_request(cert, issuer) try: ocsp_response = ocsp_response_cache[ocsp_request] @@ -349,7 +350,7 @@ def _get_ocsp_response( return ocsp_response -def _ocsp_callback(conn: Connection, ocsp_bytes: bytes, user_data: Optional[_CallbackData]) -> bool: +def _ocsp_callback(conn: Connection, ocsp_bytes: bytes, user_data: _CallbackData | None) -> bool: """Callback for use with OpenSSL.SSL.Context.set_ocsp_client_callback.""" # always pass in user_data but OpenSSL requires it be optional assert user_data diff --git a/pymongo/operations.py b/pymongo/operations.py index 99b6a00c52..1a737c05fc 100644 --- a/pymongo/operations.py +++ b/pymongo/operations.py @@ -25,11 +25,9 @@ TYPE_CHECKING, Any, Generic, - Optional, - Union, + cast, ) -from bson.raw_bson import RawBSONDocument from pymongo import helpers_shared from pymongo.collation import validate_collation_or_none from pymongo.common import validate_is_mapping, validate_list @@ -39,14 +37,13 @@ from pymongo.write_concern import validate_boolean if TYPE_CHECKING: + from bson.raw_bson import RawBSONDocument from pymongo.typings import _AgnosticBulk, _AgnosticClientBulk # Hint supports index name, "myIndex", a list of either strings or index pairs: [('x', 1), ('y', -1), 'z''], or a dictionary -_IndexList = Union[ - Sequence[Union[str, tuple[str, Union[int, str, Mapping[str, Any]]]]], Mapping[str, Any] -] -_IndexKeyHint = Union[str, _IndexList] +_IndexList = Sequence[str | tuple[str, int | str | Mapping[str, Any]]] | Mapping[str, Any] +_IndexKeyHint = str | _IndexList class _Op(str, enum.Enum): @@ -105,7 +102,7 @@ class InsertOne(Generic[_DocumentType]): "_namespace", ) - def __init__(self, document: _DocumentType, namespace: Optional[str] = None) -> None: + def __init__(self, document: _DocumentType, namespace: str | None = None) -> None: """Create an InsertOne instance. For use with :meth:`~pymongo.asynchronous.collection.AsyncCollection.bulk_write`, :meth:`~pymongo.collection.Collection.bulk_write`, @@ -141,14 +138,15 @@ def __repr__(self) -> str: return f"{self.__class__.__name__}({self._doc!r}, {self._namespace!r})" return f"{self.__class__.__name__}({self._doc!r})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if type(other) is type(self): - return other._doc == self._doc and other._namespace == self._namespace + _other = cast("InsertOne[_DocumentType]", other) + return _other._doc == self._doc and _other._namespace == self._namespace return NotImplemented __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other @@ -165,14 +163,14 @@ class _DeleteOp: def __init__( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, ) -> None: if filter is not None: validate_is_mapping("filter", filter) if hint is not None and not isinstance(hint, str): - self._hint: Union[str, dict[str, Any], None] = helpers_shared._index_document(hint) + self._hint: str | dict[str, Any] | None = helpers_shared._index_document(hint) else: self._hint = hint @@ -180,13 +178,14 @@ def __init__( self._collation = collation self._namespace = namespace - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if type(other) is type(self): + _other = cast("_DeleteOp", other) return ( - other._filter, - other._collation, - other._hint, - other._namespace, + _other._filter, + _other._collation, + _other._hint, + _other._namespace, ) == ( self._filter, self._collation, @@ -197,7 +196,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: @@ -214,9 +213,9 @@ class DeleteOne(_DeleteOp): def __init__( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, ) -> None: """Create a DeleteOne instance. @@ -275,9 +274,9 @@ class DeleteMany(_DeleteOp): def __init__( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, ) -> None: """Create a DeleteMany instance. @@ -344,12 +343,12 @@ class ReplaceOne(Generic[_DocumentType]): def __init__( self, filter: Mapping[str, Any], - replacement: Union[_DocumentType, RawBSONDocument], - upsert: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, - sort: Optional[Mapping[str, Any]] = None, + replacement: _DocumentType | RawBSONDocument, + upsert: bool | None = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Create a ReplaceOne instance. @@ -385,7 +384,7 @@ def __init__( if upsert is not None: validate_boolean("upsert", upsert) if hint is not None and not isinstance(hint, str): - self._hint: Union[str, dict[str, Any], None] = helpers_shared._index_document(hint) + self._hint: str | dict[str, Any] | None = helpers_shared._index_document(hint) else: self._hint = hint @@ -423,16 +422,17 @@ def _add_to_client_bulk(self, bulkobj: _AgnosticClientBulk) -> None: sort=self._sort, ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if type(other) is type(self): + _other = cast("ReplaceOne[_DocumentType]", other) return ( - other._filter, - other._doc, - other._upsert, - other._collation, - other._hint, - other._namespace, - other._sort, + _other._filter, + _other._doc, + _other._upsert, + _other._collation, + _other._hint, + _other._namespace, + _other._sort, ) == ( self._filter, self._doc, @@ -446,7 +446,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: @@ -472,13 +472,13 @@ class _UpdateOp: def __init__( self, filter: Mapping[str, Any], - doc: Union[Mapping[str, Any], _Pipeline], - upsert: Optional[bool], - collation: Optional[_CollationIn], - array_filters: Optional[list[Mapping[str, Any]]], - hint: Optional[_IndexKeyHint], - namespace: Optional[str], - sort: Optional[Mapping[str, Any]], + doc: Mapping[str, Any] | _Pipeline, + upsert: bool | None, + collation: _CollationIn | None, + array_filters: list[Mapping[str, Any]] | None, + hint: _IndexKeyHint | None, + namespace: str | None, + sort: Mapping[str, Any] | None, ): if filter is not None: validate_is_mapping("filter", filter) @@ -487,7 +487,7 @@ def __init__( if array_filters is not None: validate_list("array_filters", array_filters) if hint is not None and not isinstance(hint, str): - self._hint: Union[str, dict[str, Any], None] = helpers_shared._index_document(hint) + self._hint: str | dict[str, Any] | None = helpers_shared._index_document(hint) else: self._hint = hint self._filter = filter @@ -523,7 +523,7 @@ def __eq__(self, other: object) -> bool: __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: @@ -540,13 +540,13 @@ class UpdateOne(_UpdateOp): def __init__( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], - upsert: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[list[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, - sort: Optional[Mapping[str, Any]] = None, + update: Mapping[str, Any] | _Pipeline, + upsert: bool | None = None, + collation: _CollationIn | None = None, + array_filters: list[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, + sort: Mapping[str, Any] | None = None, ) -> None: """Represents an update_one operation. @@ -625,12 +625,12 @@ class UpdateMany(_UpdateOp): def __init__( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], - upsert: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[list[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - namespace: Optional[str] = None, + update: Mapping[str, Any] | _Pipeline, + upsert: bool | None = None, + collation: _CollationIn | None = None, + array_filters: list[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + namespace: str | None = None, ) -> None: """Create an UpdateMany instance. @@ -793,8 +793,8 @@ class SearchIndexModel: def __init__( self, definition: Mapping[str, Any], - name: Optional[str] = None, - type: Optional[str] = None, + name: str | None = None, + type: str | None = None, **kwargs: Any, ) -> None: """Create a Search Index instance. diff --git a/pymongo/periodic_executor.py b/pymongo/periodic_executor.py index 88149115ff..c20dfdfec8 100644 --- a/pymongo/periodic_executor.py +++ b/pymongo/periodic_executor.py @@ -21,7 +21,7 @@ import threading import time import weakref -from typing import Any, Optional +from typing import Any from pymongo import _csot, _op_id from pymongo.lock import _create_lock @@ -35,7 +35,7 @@ def __init__( interval: float, min_interval: float, target: Any, - name: Optional[str] = None, + name: str | None = None, ): """Run a target function periodically on a background task. @@ -52,7 +52,7 @@ def __init__( self._min_interval = min_interval self._target = target self._stopped = False - self._task: Optional[asyncio.Task[Any]] = None + self._task: asyncio.Task[Any] | None = None self._name = name self._skip_sleep = False @@ -75,10 +75,19 @@ def close(self, dummy: Any = None) -> None: callback; see monitor.py. """ self._stopped = True - if self._task is not None: + if self._task is None: + return + try: + current = asyncio.current_task() + except RuntimeError: + # close() also runs as a weakref callback, off the event loop. + current = None + # Never cancel the calling task: self-cancellation aborts close() + # mid-way and leaves the monitor dead (PYTHON-6226). + if self._task is not current: self._task.cancel() - async def join(self, timeout: Optional[int] = None) -> None: + async def join(self, timeout: int | None = None) -> None: if self._task is not None: await asyncio.wait([self._task], timeout=timeout) # type-ignore: [arg-type] @@ -143,7 +152,7 @@ def __init__( interval: float, min_interval: float, target: Any, - name: Optional[str] = None, + name: str | None = None, ): """Run a target function periodically on a background thread. @@ -164,7 +173,7 @@ def __init__( self._min_interval = min_interval self._target = target self._stopped = False - self._thread: Optional[threading.Thread] = None + self._thread: threading.Thread | None = None self._name = name self._skip_sleep = False self._thread_will_exit = False @@ -236,7 +245,7 @@ def close(self, dummy: Any = None) -> None: """ self._stopped = True - def join(self, timeout: Optional[int] = None) -> None: + def join(self, timeout: int | None = None) -> None: if self._thread is not None: try: self._thread.join(timeout) diff --git a/pymongo/pool_options.py b/pymongo/pool_options.py index 45a9adf5da..98ca7f657d 100644 --- a/pymongo/pool_options.py +++ b/pymongo/pool_options.py @@ -23,10 +23,9 @@ import os import platform import sys -from collections.abc import MutableMapping from contextlib import AbstractContextManager, nullcontext from pathlib import Path -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any import bson from pymongo import __version__ @@ -41,6 +40,8 @@ from pymongo.lock import _create_lock if TYPE_CHECKING: + from collections.abc import MutableMapping + from pymongo.auth_shared import MongoCredential from pymongo.compression_support import CompressionSettings from pymongo.driver_info import DriverInfo @@ -106,7 +107,8 @@ def get_container_env_info() -> dict[str, str]: """Returns the runtime and orchestrator of a container. - If neither value is present, the metadata client.env.container field will be omitted.""" + If neither value is present, the metadata client.env.container field will be omitted. + """ container = {} if Path(DOCKER_ENV_PATH).exists(): @@ -165,7 +167,7 @@ def _is_faas() -> bool: _MAX_AGENT_SIZE = 64 -def _metadata_agent() -> Optional[str]: +def _metadata_agent() -> str | None: """Detect a coding agent from the environment for client.env.agent.""" for var, name in _AGENT_ENV_VARS: if (os.getenv(var) or "").strip(): @@ -181,7 +183,7 @@ def _metadata_agent() -> Optional[str]: return agent.encode(errors="ignore")[:_MAX_AGENT_SIZE].decode(errors="ignore") -def _getenv_int(key: str) -> Optional[int]: +def _getenv_int(key: str) -> int | None: """Like os.getenv but returns an int, or None if the value is missing/malformed.""" val = os.getenv(key) if not val: @@ -333,7 +335,7 @@ def _truncate_metadata(metadata: MutableMapping[str, Any]) -> None: # driver) are dropped first since they cost nothing. name_str = driver.get("name", "") version_str = driver.get("version", "") - raw_pairs = list(zip(name_str.split("|"), version_str.split("|"))) + raw_pairs = list(zip(name_str.split("|"), version_str.split("|"), strict=True)) pairs = [(name, version) for name, version in raw_pairs if name or version] new_name = "|".join(name for name, _ in pairs) new_version = "|".join(version for _, version in pairs) @@ -409,22 +411,22 @@ def __init__( self, max_pool_size: int = MAX_POOL_SIZE, min_pool_size: int = MIN_POOL_SIZE, - max_idle_time_seconds: Optional[int] = MAX_IDLE_TIME_SEC, - connect_timeout: Optional[float] = None, - socket_timeout: Optional[float] = None, - wait_queue_timeout: Optional[int] = WAIT_QUEUE_TIMEOUT, - ssl_context: Optional[SSLContext] = None, + max_idle_time_seconds: int | None = MAX_IDLE_TIME_SEC, + connect_timeout: float | None = None, + socket_timeout: float | None = None, + wait_queue_timeout: int | None = WAIT_QUEUE_TIMEOUT, + ssl_context: SSLContext | None = None, tls_allow_invalid_hostnames: bool = False, - event_listeners: Optional[_EventListeners] = None, - appname: Optional[str] = None, - driver: Optional[DriverInfo] = None, - compression_settings: Optional[CompressionSettings] = None, + event_listeners: _EventListeners | None = None, + appname: str | None = None, + driver: DriverInfo | None = None, + compression_settings: CompressionSettings | None = None, max_connecting: int = MAX_CONNECTING, pause_enabled: bool = True, - server_api: Optional[ServerApi] = None, - load_balanced: Optional[bool] = None, - credentials: Optional[MongoCredential] = None, - is_sync: Optional[bool] = True, + server_api: ServerApi | None = None, + load_balanced: bool | None = None, + credentials: MongoCredential | None = None, + is_sync: bool | None = True, ): self.__max_pool_size = max_pool_size self.__min_pool_size = min_pool_size @@ -524,7 +526,7 @@ def _update_metadata(self, driver: DriverInfo) -> None: self.__appended_drivers.add(driver) @property - def _credentials(self) -> Optional[MongoCredential]: + def _credentials(self) -> MongoCredential | None: """A :class:`~pymongo.auth.MongoCredentials` instance or None.""" return self.__credentials @@ -583,7 +585,7 @@ def pause_enabled(self) -> bool: return self.__pause_enabled @property - def max_idle_time_seconds(self) -> Optional[int]: + def max_idle_time_seconds(self) -> int | None: """The maximum number of seconds that a connection can remain idle in the pool before being removed and replaced. Defaults to `None` (no limit). @@ -591,24 +593,24 @@ def max_idle_time_seconds(self) -> Optional[int]: return self.__max_idle_time_seconds @property - def connect_timeout(self) -> Optional[float]: + def connect_timeout(self) -> float | None: """How long a connection can take to be opened before timing out.""" return self.__connect_timeout @property - def socket_timeout(self) -> Optional[float]: + def socket_timeout(self) -> float | None: """How long a send or receive on a socket can take before timing out.""" return self.__socket_timeout @property - def wait_queue_timeout(self) -> Optional[int]: + def wait_queue_timeout(self) -> int | None: """How long a thread will wait for a socket from the pool if the pool has no free sockets. """ return self.__wait_queue_timeout @property - def _ssl_context(self) -> Optional[SSLContext]: + def _ssl_context(self) -> SSLContext | None: """An SSLContext instance or None.""" return self.__ssl_context @@ -618,22 +620,22 @@ def tls_allow_invalid_hostnames(self) -> bool: return self.__tls_allow_invalid_hostnames @property - def _event_listeners(self) -> Optional[_EventListeners]: + def _event_listeners(self) -> _EventListeners | None: """An instance of pymongo.monitoring._EventListeners.""" return self.__event_listeners @property - def appname(self) -> Optional[str]: + def appname(self) -> str | None: """The application name, for sending with hello in server handshake.""" return self.__appname @property - def driver(self) -> Optional[DriverInfo]: + def driver(self) -> DriverInfo | None: """Driver name and version, for sending with hello in handshake.""" return self.__driver @property - def _compression_settings(self) -> Optional[CompressionSettings]: + def _compression_settings(self) -> CompressionSettings | None: return self.__compression_settings @property @@ -642,11 +644,11 @@ def metadata(self) -> dict[str, Any]: return self.__metadata.copy() @property - def server_api(self) -> Optional[ServerApi]: + def server_api(self) -> ServerApi | None: """A pymongo.server_api.ServerApi or None.""" return self.__server_api @property - def load_balanced(self) -> Optional[bool]: + def load_balanced(self) -> bool | None: """True if this Pool is configured in load balanced mode.""" return self.__load_balanced diff --git a/pymongo/pool_shared.py b/pymongo/pool_shared.py index 48a0a27bf1..83a10ef5ae 100644 --- a/pymongo/pool_shared.py +++ b/pymongo/pool_shared.py @@ -26,22 +26,18 @@ import sys import time import weakref -from collections.abc import MutableMapping from typing import ( TYPE_CHECKING, Any, Generic, NoReturn, - Optional, Protocol, TypeVar, - Union, ) from pymongo import _csot from pymongo._telemetry import _CmapTelemetry from pymongo.asynchronous.helpers import _getaddrinfo -from pymongo.auth_shared import _AuthContext from pymongo.common import MAX_BSON_SIZE, MAX_MESSAGE_SIZE, MAX_WIRE_VERSION, MAX_WRITE_BATCH_SIZE from pymongo.errors import ( # type:ignore[attr-defined] AutoReconnect, @@ -63,15 +59,18 @@ NetworkingInterfaceBase, PyMongoProtocol, ) -from pymongo.pool_options import PoolOptions from pymongo.server_api import _add_to_command from pymongo.socket_checker import SocketChecker from pymongo.ssl_support import SSL_EOF_ERRORS, PYSSLError, SSLError, _has_sni SSLErrors = (PYSSLError, SSLError) if TYPE_CHECKING: + from collections.abc import MutableMapping + from bson.objectid import ObjectId + from pymongo.auth_shared import _AuthContext from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address, _AgnosticClientSession, _AgnosticMongoClient @@ -96,9 +95,9 @@ class _ConnectionTelemetryInfo(Protocol): """Protocol for connection fields consumed by :class:`~pymongo._telemetry._CommandTelemetry`.""" id: int - server_connection_id: Optional[int] + server_connection_id: int | None address: tuple[str, int] - service_id: Optional[ObjectId] + service_id: ObjectId | None class _AgnosticBaseConnection(_ConnectionTelemetryInfo, Generic[_PoolT]): @@ -132,12 +131,12 @@ def __init__( self.listeners = pool.opts._event_listeners self._telemetry = pool._telemetry self.compression_settings = pool.opts._compression_settings - self.compression_context: Union[SnappyContext, ZlibContext, ZstdContext, None] = None + self.compression_context: SnappyContext | ZlibContext | ZstdContext | None = None self.socket_checker: SocketChecker = SocketChecker() - self.oidc_token_gen_id: Optional[int] = None + self.oidc_token_gen_id: int | None = None # Support for mechanism negotiation on the initial handshake. - self.negotiated_mechs: Optional[list[str]] = None - self.auth_ctx: Optional[_AuthContext] = None + self.negotiated_mechs: list[str] | None = None + self.auth_ctx: _AuthContext | None = None # The pool's generation changes with each reset() so we can close # sockets created before the last reset. @@ -148,8 +147,8 @@ def __init__( self.opts = pool.opts self.more_to_come: bool = False # For load balancer support. - self.service_id: Optional[ObjectId] = None - self.server_connection_id: Optional[int] = None + self.service_id: ObjectId | None = None + self.server_connection_id: int | None = None # When executing a transaction in load balancing mode, this flag is # set to true to indicate that the session now owns the connection. self.pinned_txn = False @@ -160,14 +159,14 @@ def __init__( # For gossiping $clusterTime from the connection handshake to the client. self._cluster_time = None - def set_conn_timeout(self, timeout: Optional[float]) -> None: + def set_conn_timeout(self, timeout: float | None) -> None: """Cache last timeout to avoid duplicate calls to conn.settimeout.""" if timeout == self.last_timeout: return self.last_timeout = timeout self.conn.get_conn.settimeout(timeout) - def apply_timeout(self, cmd: Optional[MutableMapping[str, Any]]) -> Optional[float]: + def apply_timeout(self, cmd: MutableMapping[str, Any] | None) -> float | None: # CSOT: use remaining timeout when set. timeout = _csot.remaining() if timeout is None: @@ -217,7 +216,7 @@ def _raise_if_not_writable(self) -> None: raise NotPrimaryError("not primary", {"ok": 0, "errmsg": "not primary", "code": 10107}) def validate_session( - self, client: Optional[_AgnosticMongoClient], session: Optional[_AgnosticClientSession] + self, client: _AgnosticMongoClient | None, session: _AgnosticClientSession | None ) -> None: """Validate this session before use with client. @@ -232,8 +231,8 @@ def validate_session( def send_cluster_time( self, command: MutableMapping[str, Any], - session: Optional[_AgnosticClientSession], - client: Optional[_AgnosticMongoClient], + session: _AgnosticClientSession | None, + client: _AgnosticMongoClient | None, ) -> None: """Add $clusterTime.""" if client: @@ -254,10 +253,10 @@ def idle_time_seconds(self) -> float: """Seconds since this socket was last checked into its pool.""" return time.monotonic() - self.last_checkin_time - def __eq__(self, other: Any) -> bool: - return self.conn == other.conn + def __eq__(self, other: object) -> bool: + return self.conn == other.conn # type: ignore[attr-defined] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -272,7 +271,7 @@ def __init__( address: _Address, options: PoolOptions, is_sdam: bool = False, - client_id: Optional[ObjectId] = None, + client_id: ObjectId | None = None, ): """ :param address: a (hostname, port) tuple @@ -295,7 +294,7 @@ def __init__( # Monotonically increasing connection ID required for CMAP Events. self.next_connection_id = 1 # Track whether the sockets in this pool are writeable or not. - self.is_writable: Optional[bool] = None + self.is_writable: bool | None = None # Keep track of resets, so we notice sockets created before the most # recent reset and close them. @@ -311,7 +310,7 @@ def __init__( self.max_pool_size = float("inf") self._pending = 0 self._max_connecting = self.opts.max_connecting - self._ssl_session_cache: Optional[list[Any]] = ( + self._ssl_session_cache: list[Any] | None = ( [None] if self.opts._ssl_context is not None and not _TLS_SESSION_REUSE_LEAKS else None ) self._telemetry = _CmapTelemetry( @@ -331,7 +330,7 @@ def __init__( def closed(self) -> bool: return self.state == PoolState.CLOSED - def stale_generation(self, gen: int, service_id: Optional[ObjectId]) -> bool: + def stale_generation(self, gen: int, service_id: ObjectId | None) -> bool: return self.gen.stale(gen, service_id) def _handle_connection_error(self, error: BaseException) -> None: @@ -376,7 +375,7 @@ def _restore_applied(self, applied: int) -> None: def _checkin_apply( self, conn: _ConnT, txn: bool, cursor: bool, forked: bool - ) -> tuple[Optional[str], bool, bool]: + ) -> tuple[str | None, bool, bool]: """Apply checkin accounting; caller holds ``size_cond``. No cooperative I/O, so safe while a gevent greenlet unwinds. Returns @@ -390,7 +389,7 @@ def _checkin_apply( self.requests -= 1 self.active_sockets -= 1 self.operation_count -= 1 - close_conn_reason: Optional[str] = None + close_conn_reason: str | None = None emit_closed = False appended = False if not forked: @@ -429,7 +428,7 @@ def _raise_wait_queue_timeout(self, checkout_started_time: float) -> NoReturn: ) -def _get_ssl_session(ssl_sock: Any) -> Optional[Any]: +def _get_ssl_session(ssl_sock: Any) -> Any | None: """Return the TLS session from an SSL socket, handling both PyOpenSSL and stdlib ssl.""" if hasattr(ssl_sock, "get_session"): return ssl_sock.get_session() @@ -514,8 +513,8 @@ def _set_keepalive_times(sock: socket.socket) -> None: def _raise_connection_failure( address: Any, error: Exception, - msg_prefix: Optional[str] = None, - timeout_details: Optional[dict[str, float]] = None, + msg_prefix: str | None = None, + timeout_details: dict[str, float] | None = None, ) -> NoReturn: """Convert a socket.error to ConnectionFailure and raise it.""" host, port = address @@ -528,7 +527,7 @@ def _raise_connection_failure( msg = msg_prefix + msg if "configured timeouts" not in msg: msg += format_timeout_details(timeout_details) - if isinstance(error, socket.timeout) or ( + if isinstance(error, TimeoutError) or ( isinstance(error, SSLErrors) and "timed out" in str(error) ): raise NetworkTimeout(msg) from error @@ -563,7 +562,7 @@ def __init__(self) -> None: # Overall pool generation. self._generation = 0 - def get(self, service_id: Optional[ObjectId]) -> int: + def get(self, service_id: ObjectId | None) -> int: """Get the generation for the given service_id.""" if service_id is None: return self._generation @@ -573,7 +572,7 @@ def get_overall(self) -> int: """Get the Pool's overall generation.""" return self._generation - def inc(self, service_id: Optional[ObjectId]) -> None: + def inc(self, service_id: ObjectId | None) -> None: """Increment the generation for the given service_id.""" self._generation += 1 if service_id is None: @@ -582,7 +581,7 @@ def inc(self, service_id: Optional[ObjectId]) -> None: else: self._generations[service_id] += 1 - def stale(self, gen: int, service_id: Optional[ObjectId]) -> bool: + def stale(self, gen: int, service_id: ObjectId | None) -> bool: """Return if the given generation for a given service_id is stale.""" return gen != self.get(service_id) @@ -645,7 +644,7 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) # Socket needs to be non-blocking during connection to not block the event loop @@ -655,9 +654,9 @@ async def _async_create_connection(address: _Address, options: PoolOptions) -> s ) sock.settimeout(timeout) return sock - except asyncio.TimeoutError as e: + except TimeoutError as e: sock.close() - err = socket.timeout("timed out") + err = TimeoutError("timed out") err.__cause__ = e except OSError as e: sock.close() @@ -684,7 +683,7 @@ def _close_late_socket(future: asyncio.Future[Any]) -> None: async def _async_wrap_socket_tls( sock: socket.socket, address: _Address, options: PoolOptions -) -> Union[socket.socket, _sslConn]: +) -> socket.socket | _sslConn: """Given a connected socket, (host, port), and PoolOptions, apply TLS. The handshake, SNI, and certificate/hostname verification all target @@ -749,7 +748,7 @@ async def _async_wrap_socket_tls( async def _async_configured_socket( address: _Address, options: PoolOptions -) -> Union[socket.socket, _sslConn]: +) -> socket.socket | _sslConn: """Given (host, port) and PoolOptions, return a raw configured socket. Can raise socket.error, ConnectionFailure, or _CertificateError. @@ -763,7 +762,7 @@ async def _async_configured_socket( async def _configured_protocol_interface( address: _Address, options: PoolOptions, - ssl_session_cache: Optional[list[Any]] = None, + ssl_session_cache: list[Any] | None = None, ) -> AsyncNetworkingInterface: """Given (host, port) and PoolOptions, return a configured AsyncNetworkingInterface. @@ -891,7 +890,7 @@ def _create_connection(address: _Address, options: PoolOptions) -> socket.socket if timeout is None: timeout = options.connect_timeout elif timeout <= 0: - raise socket.timeout("timed out") + raise TimeoutError("timed out") sock.settimeout(timeout) sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, True) _set_keepalive_times(sock) @@ -912,7 +911,7 @@ def _create_connection(address: _Address, options: PoolOptions) -> socket.socket def _wrap_socket_tls( sock: socket.socket, address: _Address, options: PoolOptions -) -> Union[socket.socket, _sslConn]: +) -> socket.socket | _sslConn: """Given a connected socket, (host, port), and PoolOptions, apply TLS. The handshake, SNI, and certificate/hostname verification all target @@ -964,7 +963,7 @@ def _wrap_socket_tls( return ssl_sock -def _configured_socket(address: _Address, options: PoolOptions) -> Union[socket.socket, _sslConn]: +def _configured_socket(address: _Address, options: PoolOptions) -> socket.socket | _sslConn: """Given (host, port) and PoolOptions, return a raw configured socket. Can raise socket.error, ConnectionFailure, or _CertificateError. @@ -978,7 +977,7 @@ def _configured_socket(address: _Address, options: PoolOptions) -> Union[socket. def _configured_socket_interface( address: _Address, options: PoolOptions, - ssl_session_cache: Optional[list[Any]] = None, + ssl_session_cache: list[Any] | None = None, ) -> NetworkingInterface: """Given (host, port) and PoolOptions, return a NetworkingInterface wrapping a configured socket. diff --git a/pymongo/pyopenssl_context.py b/pymongo/pyopenssl_context.py index 452912d686..10e8af1d0b 100644 --- a/pymongo/pyopenssl_context.py +++ b/pymongo/pyopenssl_context.py @@ -20,14 +20,12 @@ from __future__ import annotations -import socket as _socket import ssl as _stdlibssl import sys as _sys import time as _time -from collections.abc import Callable from errno import EINTR as _EINTR from ipaddress import ip_address as _ip_address -from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union +from typing import TYPE_CHECKING, Any, TypeVar import cryptography.x509 as x509 import service_identity @@ -43,6 +41,8 @@ from pymongo.write_concern import validate_boolean if TYPE_CHECKING: + import socket as _socket + from collections.abc import Callable from ssl import VerifyMode @@ -114,7 +114,7 @@ class _sslConn(_SSL.Connection): def __init__( self, ctx: _SSL.Context, - sock: Optional[_socket.socket], + sock: _socket.socket | None, suppress_ragged_eofs: bool, ): self.socket_checker = _SocketChecker() @@ -131,11 +131,11 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: except BLOCKING_IO_ERRORS as exc: # Do not retry if the connection is in non-blocking mode. if timeout == 0: - raise exc + raise # Check for closed socket. if self.fileno() == -1: if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None raise SSLError("Underlying socket has been closed") from None if isinstance(exc, _SSL.WantReadError): want_read = True @@ -148,7 +148,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: want_write = True self.socket_checker.select(self, want_read, want_write, timeout) if timeout and _time.monotonic() - start > timeout: - raise _socket.timeout("timed out") from None + raise TimeoutError("timed out") from None continue def do_handshake(self, *args: Any, **kwargs: Any) -> None: @@ -197,8 +197,8 @@ class _CallbackData: """Data class which is passed to the OCSP callback.""" def __init__(self) -> None: - self.trusted_ca_certs: Optional[list[x509.Certificate]] = None - self.check_ocsp_endpoint: Optional[bool] = None + self.trusted_ca_certs: list[x509.Certificate] | None = None + self.check_ocsp_endpoint: bool | None = None self.ocsp_response_cache = _OCSPCache() @@ -253,7 +253,7 @@ def __set_check_hostname(self, value: Any) -> None: check_hostname = property(__get_check_hostname, __set_check_hostname) - def __get_check_ocsp_endpoint(self) -> Optional[bool]: + def __get_check_ocsp_endpoint(self) -> bool | None: return self._callback_data.check_ocsp_endpoint def __set_check_ocsp_endpoint(self, value: bool) -> None: @@ -276,9 +276,9 @@ def __set_options(self, value: int) -> None: def load_cert_chain( self, - certfile: Union[str, bytes], - keyfile: Union[str, bytes, None] = None, - password: Optional[str] = None, + certfile: str | bytes, + keyfile: str | bytes | None = None, + password: str | None = None, ) -> None: """Load a private key and the corresponding certificate. The certfile string must be the path to a single file in PEM format containing the @@ -292,7 +292,7 @@ def load_cert_chain( # Password callback MUST be set first or it will be ignored. if password: - def _pwcb(_max_length: int, _prompt_twice: bool, _user_data: Optional[bytes]) -> bytes: + def _pwcb(_max_length: int, _prompt_twice: bool, _user_data: bytes | None) -> bytes: # XXX:We could check the password length against what OpenSSL # tells us is the max, but we can't raise an exception, so... # warn? @@ -304,9 +304,7 @@ def _pwcb(_max_length: int, _prompt_twice: bool, _user_data: Optional[bytes]) -> self._ctx.use_privatekey_file(keyfile or certfile) self._ctx.check_privatekey() - def load_verify_locations( - self, cafile: Optional[str] = None, capath: Optional[str] = None - ) -> None: + def load_verify_locations(self, cafile: str | None = None, capath: str | None = None) -> None: """Load a set of "certification authority"(CA) certificates used to validate other peers' certificates when `~verify_mode` is other than ssl.CERT_NONE. @@ -368,8 +366,8 @@ def wrap_socket( server_side: bool = False, do_handshake_on_connect: bool = True, suppress_ragged_eofs: bool = True, - server_hostname: Optional[str] = None, - session: Optional[_SSL.Session] = None, + server_hostname: str | None = None, + session: _SSL.Session | None = None, ) -> _sslConn: """Wrap an existing Python socket connection and return a TLS socket object. diff --git a/pymongo/read_concern.py b/pymongo/read_concern.py index 9a11c8f562..21e66aa52c 100644 --- a/pymongo/read_concern.py +++ b/pymongo/read_concern.py @@ -19,7 +19,7 @@ from __future__ import annotations -from typing import Any, Optional +from typing import Any class ReadConcern: @@ -35,14 +35,14 @@ class ReadConcern: """ - def __init__(self, level: Optional[str] = None) -> None: + def __init__(self, level: str | None = None) -> None: if level is None or isinstance(level, str): self.__level = level else: raise TypeError(f"level must be a string or None, not {type(level)}") @property - def level(self) -> Optional[str]: + def level(self) -> str | None: """The read concern level.""" return self.__level @@ -66,7 +66,7 @@ def document(self) -> dict[str, Any]: doc["level"] = self.level return doc - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, ReadConcern): return self.document == other.document return NotImplemented diff --git a/pymongo/read_preferences.py b/pymongo/read_preferences.py index 204bb49101..721725563e 100644 --- a/pymongo/read_preferences.py +++ b/pymongo/read_preferences.py @@ -22,7 +22,7 @@ import warnings from collections import abc from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from pymongo import max_staleness_selectors from pymongo.errors import ConfigurationError @@ -55,7 +55,7 @@ _TagSets = Sequence[Mapping[str, Any]] -def _validate_tag_sets(tag_sets: Optional[_TagSets]) -> Optional[_TagSets]: +def _validate_tag_sets(tag_sets: _TagSets | None) -> _TagSets | None: """Validate tag sets for a MongoClient.""" if tag_sets is None: return tag_sets @@ -97,7 +97,7 @@ def _validate_max_staleness(max_staleness: Any) -> int: return max_staleness -def _validate_hedge(hedge: Optional[_Hedge]) -> Optional[_Hedge]: +def _validate_hedge(hedge: _Hedge | None) -> _Hedge | None: """Validate hedge.""" if hedge is None: return None @@ -121,9 +121,9 @@ class _ServerMode: def __init__( self, mode: int, - tag_sets: Optional[_TagSets] = None, + tag_sets: _TagSets | None = None, max_staleness: int = -1, - hedge: Optional[_Hedge] = None, + hedge: _Hedge | None = None, ) -> None: self.__mongos_mode = _MONGOS_MODES[mode] self.__mode = mode @@ -189,7 +189,7 @@ def max_staleness(self) -> int: return self.__max_staleness @property - def hedge(self) -> Optional[_Hedge]: + def hedge(self) -> _Hedge | None: """**DEPRECATED** - The read preference 'hedge' option is deprecated in PyMongo 4.12+ because hedged reads are deprecated in MongoDB version 8.0+. Support for 'hedge' will be removed in PyMongo 5.0. The read preference ``hedge`` parameter. @@ -236,7 +236,7 @@ def min_wire_version(self) -> int: def __repr__(self) -> str: return f"{self.name}(tag_sets={self.__tag_sets!r}, max_staleness={self.__max_staleness!r}, hedge={self.__hedge!r})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, _ServerMode): return ( self.mode == other.mode @@ -248,7 +248,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __getstate__(self) -> dict[str, Any]: @@ -297,7 +297,7 @@ def __call__(self, selection: Selection) -> Selection: def __repr__(self) -> str: return "Primary()" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, _ServerMode): return other.mode == _PRIMARY return NotImplemented @@ -336,9 +336,9 @@ class PrimaryPreferred(_ServerMode): def __init__( self, - tag_sets: Optional[_TagSets] = None, + tag_sets: _TagSets | None = None, max_staleness: int = -1, - hedge: Optional[_Hedge] = None, + hedge: _Hedge | None = None, ) -> None: super().__init__(_PRIMARY_PREFERRED, tag_sets, max_staleness, hedge) @@ -378,9 +378,9 @@ class Secondary(_ServerMode): def __init__( self, - tag_sets: Optional[_TagSets] = None, + tag_sets: _TagSets | None = None, max_staleness: int = -1, - hedge: Optional[_Hedge] = None, + hedge: _Hedge | None = None, ) -> None: super().__init__(_SECONDARY, tag_sets, max_staleness, hedge) @@ -421,9 +421,9 @@ class SecondaryPreferred(_ServerMode): def __init__( self, - tag_sets: Optional[_TagSets] = None, + tag_sets: _TagSets | None = None, max_staleness: int = -1, - hedge: Optional[_Hedge] = None, + hedge: _Hedge | None = None, ) -> None: super().__init__(_SECONDARY_PREFERRED, tag_sets, max_staleness, hedge) @@ -465,9 +465,9 @@ class Nearest(_ServerMode): def __init__( self, - tag_sets: Optional[_TagSets] = None, + tag_sets: _TagSets | None = None, max_staleness: int = -1, - hedge: Optional[_Hedge] = None, + hedge: _Hedge | None = None, ) -> None: super().__init__(_NEAREST, tag_sets, max_staleness, hedge) @@ -522,7 +522,7 @@ def __getattr__(self, name: str) -> Any: def make_read_preference( - mode: int, tag_sets: Optional[_TagSets], max_staleness: int = -1 + mode: int, tag_sets: _TagSets | None, max_staleness: int = -1 ) -> _ServerMode: if mode == _PRIMARY: if tag_sets not in (None, [{}]): @@ -614,7 +614,7 @@ def read_pref_mode_from_name(name: str) -> int: class MovingAverage: """Tracks an exponentially-weighted moving average.""" - average: Optional[float] + average: float | None def __init__(self) -> None: self.average = None @@ -629,7 +629,7 @@ def add_sample(self, sample: float) -> None: # average with alpha = 0.2. self.average = 0.8 * self.average + 0.2 * sample - def get(self) -> Optional[float]: + def get(self) -> float | None: """Get the calculated average, or None if no samples yet.""" return self.average diff --git a/pymongo/response.py b/pymongo/response.py index b832036708..366d3fee93 100644 --- a/pymongo/response.py +++ b/pymongo/response.py @@ -16,10 +16,10 @@ from __future__ import annotations -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any if TYPE_CHECKING: + from collections.abc import Mapping, Sequence from datetime import timedelta from pymongo.message import _OpMsg @@ -34,7 +34,7 @@ def __init__( data: _OpMsg, address: _Address, request_id: int, - duration: Optional[timedelta], + duration: timedelta | None, docs: Sequence[Mapping[str, Any]], ): """Represent a response from the server. @@ -66,7 +66,7 @@ def request_id(self) -> int: return self._request_id @property - def duration(self) -> Optional[timedelta]: + def duration(self) -> timedelta | None: """The duration of the operation.""" return self._duration @@ -85,7 +85,7 @@ def __init__( address: _Address, conn: _AgnosticConnection, request_id: int, - duration: Optional[timedelta], + duration: timedelta | None, docs: list[_DocumentOut], more_to_come: bool, ): diff --git a/pymongo/results.py b/pymongo/results.py index 594a28bc88..f34de54309 100644 --- a/pymongo/results.py +++ b/pymongo/results.py @@ -19,11 +19,13 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from pymongo.errors import InvalidOperation +if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + class _WriteResult: """Base class for write result classes.""" @@ -128,7 +130,7 @@ class UpdateResult(_WriteResult): def __init__( self, - raw_result: Optional[Mapping[str, Any]], + raw_result: Mapping[str, Any] | None, acknowledged: bool, in_client_bulk: bool = False, ): @@ -140,7 +142,7 @@ def __repr__(self) -> str: return f"{self.__class__.__name__}({self.__raw_result!r}, acknowledged={self.acknowledged})" @property - def raw_result(self) -> Optional[Mapping[str, Any]]: + def raw_result(self) -> Mapping[str, Any] | None: """The raw result document returned by the server.""" return self.__raw_result @@ -158,7 +160,7 @@ def modified_count(self) -> int: """The number of documents modified.""" self._raise_if_unacknowledged("modified_count") assert self.__raw_result is not None - return cast(int, self.__raw_result.get("nModified")) + return cast("int", self.__raw_result.get("nModified")) @property def upserted_id(self) -> Any: @@ -229,34 +231,34 @@ def bulk_api_result(self) -> dict[str, Any]: def inserted_count(self) -> int: """The number of documents inserted.""" self._raise_if_unacknowledged("inserted_count") - return cast(int, self.__bulk_api_result.get("nInserted")) + return cast("int", self.__bulk_api_result.get("nInserted")) @property def matched_count(self) -> int: """The number of documents matched for an update.""" self._raise_if_unacknowledged("matched_count") - return cast(int, self.__bulk_api_result.get("nMatched")) + return cast("int", self.__bulk_api_result.get("nMatched")) @property def modified_count(self) -> int: """The number of documents modified.""" self._raise_if_unacknowledged("modified_count") - return cast(int, self.__bulk_api_result.get("nModified")) + return cast("int", self.__bulk_api_result.get("nModified")) @property def deleted_count(self) -> int: """The number of documents deleted.""" self._raise_if_unacknowledged("deleted_count") if "nRemoved" in self.__bulk_api_result: - return cast(int, self.__bulk_api_result.get("nRemoved")) + return cast("int", self.__bulk_api_result.get("nRemoved")) else: - return cast(int, self.__bulk_api_result.get("nDeleted")) + return cast("int", self.__bulk_api_result.get("nDeleted")) @property def upserted_count(self) -> int: """The number of documents upserted.""" self._raise_if_unacknowledged("upserted_count") - return cast(int, self.__bulk_api_result.get("nUpserted")) + return cast("int", self.__bulk_api_result.get("nUpserted")) class BulkWriteResult(_BulkWriteResultBase): @@ -280,7 +282,7 @@ def __repr__(self) -> str: ) @property - def upserted_ids(self) -> Optional[dict[int, Any]]: + def upserted_ids(self) -> dict[int, Any] | None: """A map of operation index to the _id of the upserted document.""" self._raise_if_unacknowledged("upserted_ids") if self.bulk_api_result: @@ -339,7 +341,7 @@ def insert_results(self) -> Mapping[int, InsertOneResult]: self._raise_if_unacknowledged("insert_results") self._raise_if_not_verbose("insert_results") return cast( - Mapping[int, InsertOneResult], + "Mapping[int, InsertOneResult]", self.bulk_api_result.get("insertResults"), ) @@ -349,7 +351,7 @@ def update_results(self) -> Mapping[int, UpdateResult]: self._raise_if_unacknowledged("update_results") self._raise_if_not_verbose("update_results") return cast( - Mapping[int, UpdateResult], + "Mapping[int, UpdateResult]", self.bulk_api_result.get("updateResults"), ) @@ -359,6 +361,6 @@ def delete_results(self) -> Mapping[int, DeleteResult]: self._raise_if_unacknowledged("delete_results") self._raise_if_not_verbose("delete_results") return cast( - Mapping[int, DeleteResult], + "Mapping[int, DeleteResult]", self.bulk_api_result.get("deleteResults"), ) diff --git a/pymongo/saslprep.py b/pymongo/saslprep.py index 25d97721c1..7ed3c69bf9 100644 --- a/pymongo/saslprep.py +++ b/pymongo/saslprep.py @@ -16,7 +16,7 @@ from __future__ import annotations -from typing import Any, Optional +from typing import Any try: import stringprep @@ -25,7 +25,7 @@ def saslprep( data: Any, - prohibit_unassigned_code_points: Optional[bool] = True, # noqa: ARG001 + prohibit_unassigned_code_points: bool | None = True, # noqa: ARG001 ) -> Any: """SASLprep dummy""" if isinstance(data, str): @@ -55,7 +55,7 @@ def saslprep( stringprep.in_table_c9, ) - def saslprep(data: Any, prohibit_unassigned_code_points: Optional[bool] = True) -> Any: + def saslprep(data: Any, prohibit_unassigned_code_points: bool | None = True) -> Any: """An implementation of RFC4013 SASLprep. :param data: The string to SASLprep. Unicode strings diff --git a/pymongo/server_api.py b/pymongo/server_api.py index b492c4e278..736b654bb9 100644 --- a/pymongo/server_api.py +++ b/pymongo/server_api.py @@ -86,8 +86,10 @@ from __future__ import annotations -from collections.abc import MutableMapping -from typing import Any, Optional +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import MutableMapping class ServerApiVersion: @@ -104,7 +106,7 @@ class ServerApi: """MongoDB Stable API.""" def __init__( - self, version: str, strict: Optional[bool] = None, deprecation_errors: Optional[bool] = None + self, version: str, strict: bool | None = None, deprecation_errors: bool | None = None ): """Options to configure MongoDB Stable API. @@ -143,7 +145,7 @@ def version(self) -> str: return self._version @property - def strict(self) -> Optional[bool]: + def strict(self) -> bool | None: """The API strict mode setting. When set, this value is sent to the server in the "apiStrict" field. @@ -151,7 +153,7 @@ def strict(self) -> Optional[bool]: return self._strict @property - def deprecation_errors(self) -> Optional[bool]: + def deprecation_errors(self) -> bool | None: """The API deprecation errors setting. When set, this value is sent to the server in the @@ -160,7 +162,7 @@ def deprecation_errors(self) -> Optional[bool]: return self._deprecation_errors -def _add_to_command(cmd: MutableMapping[str, Any], server_api: Optional[ServerApi]) -> None: +def _add_to_command(cmd: MutableMapping[str, Any], server_api: ServerApi | None) -> None: """Internal helper which adds API versioning options to a command. :param cmd: The command. diff --git a/pymongo/server_description.py b/pymongo/server_description.py index c5bb7f9769..df8665d9e0 100644 --- a/pymongo/server_description.py +++ b/pymongo/server_description.py @@ -22,13 +22,18 @@ import time import warnings from collections.abc import Mapping -from typing import Any, Optional +from typing import TYPE_CHECKING, Any from bson import EPOCH_NAIVE -from bson.objectid import ObjectId from pymongo.hello import Hello from pymongo.server_type import SERVER_TYPE -from pymongo.typings import ClusterTime, _Address + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import ClusterTime, _Address + +if TYPE_CHECKING: + from collections.abc import Mapping class ServerDescription: @@ -71,9 +76,9 @@ class ServerDescription: def __init__( self, address: _Address, - hello: Optional[Hello[dict[str, Any]]] = None, - round_trip_time: Optional[float] = None, - error: Optional[Exception] = None, + hello: Hello[dict[str, Any]] | None = None, + round_trip_time: float | None = None, + error: Exception | None = None, min_round_trip_time: float = 0.0, ) -> None: self._address = address @@ -107,7 +112,7 @@ def __init__( if isinstance(details, dict): self._topology_version = details.get("topologyVersion") - self._last_write_date: Optional[float] + self._last_write_date: float | None if hello.last_write_date: # Convert from datetime to seconds. delta = hello.last_write_date - EPOCH_NAIVE @@ -143,12 +148,12 @@ def tags(self) -> Mapping[str, Any]: return self._tags @property - def replica_set_name(self) -> Optional[str]: + def replica_set_name(self) -> str | None: """Replica set name or None.""" return self._replica_set_name @property - def primary(self) -> Optional[tuple[str, int]]: + def primary(self) -> tuple[str, int] | None: """This server's opinion about who the primary is, or None.""" return self._primary @@ -173,19 +178,19 @@ def max_wire_version(self) -> int: return self._max_wire_version @property - def set_version(self) -> Optional[int]: + def set_version(self) -> int | None: return self._set_version @property - def election_id(self) -> Optional[ObjectId]: + def election_id(self) -> ObjectId | None: return self._election_id @property - def cluster_time(self) -> Optional[ClusterTime]: + def cluster_time(self) -> ClusterTime | None: return self._cluster_time @property - def election_tuple(self) -> tuple[Optional[int], Optional[ObjectId]]: + def election_tuple(self) -> tuple[int | None, ObjectId | None]: warnings.warn( "'election_tuple' is deprecated, use 'set_version' and 'election_id' instead", DeprecationWarning, @@ -194,15 +199,15 @@ def election_tuple(self) -> tuple[Optional[int], Optional[ObjectId]]: return self._set_version, self._election_id @property - def me(self) -> Optional[tuple[str, int]]: + def me(self) -> tuple[str, int] | None: return self._me @property - def logical_session_timeout_minutes(self) -> Optional[int]: + def logical_session_timeout_minutes(self) -> int | None: return self._ls_timeout_minutes @property - def last_write_date(self) -> Optional[float]: + def last_write_date(self) -> float | None: return self._last_write_date @property @@ -210,7 +215,7 @@ def last_update_time(self) -> float: return self._last_update_time @property - def round_trip_time(self) -> Optional[float]: + def round_trip_time(self) -> float | None: """The current average latency or None.""" # This override is for unittesting only! if self._address in self._host_to_round_trip_time: @@ -224,7 +229,7 @@ def min_round_trip_time(self) -> float: return self._min_round_trip_time @property - def error(self) -> Optional[Exception]: + def error(self) -> Exception | None: """The last error attempting to connect to the server, or None.""" return self._error @@ -257,15 +262,15 @@ def retryable_reads_supported(self) -> bool: return self._max_wire_version >= 6 @property - def topology_version(self) -> Optional[Mapping[str, Any]]: + def topology_version(self) -> Mapping[str, Any] | None: return self._topology_version - def to_unknown(self, error: Optional[Exception] = None) -> ServerDescription: + def to_unknown(self, error: Exception | None = None) -> ServerDescription: unknown = ServerDescription(self.address, error=error) unknown._topology_version = self.topology_version return unknown - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, ServerDescription): return ( (self._address == other.address) @@ -287,7 +292,7 @@ def __eq__(self, other: Any) -> bool: __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __repr__(self) -> str: diff --git a/pymongo/server_selectors.py b/pymongo/server_selectors.py index b43272f7f3..7639cfc1f3 100644 --- a/pymongo/server_selectors.py +++ b/pymongo/server_selectors.py @@ -17,7 +17,7 @@ from __future__ import annotations from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast +from typing import TYPE_CHECKING, Any, TypeVar, cast from pymongo.server_type import SERVER_TYPE @@ -54,8 +54,8 @@ def __init__( self, topology_description: TopologyDescription, server_descriptions: list[ServerDescription], - common_wire_version: Optional[int], - primary: Optional[ServerDescription], + common_wire_version: int | None, + primary: ServerDescription | None, ): self.topology_description = topology_description self.server_descriptions = server_descriptions @@ -67,11 +67,11 @@ def with_server_descriptions(self, server_descriptions: list[ServerDescription]) self.topology_description, server_descriptions, self.common_wire_version, self.primary ) - def secondary_with_max_last_write_date(self) -> Optional[ServerDescription]: + def secondary_with_max_last_write_date(self) -> ServerDescription | None: secondaries = secondary_server_selector(self) if secondaries.server_descriptions: return max( - secondaries.server_descriptions, key=lambda sd: cast(float, sd.last_write_date) + secondaries.server_descriptions, key=lambda sd: cast("float", sd.last_write_date) ) return None diff --git a/pymongo/settings_shared.py b/pymongo/settings_shared.py index 65e744be2e..d36876006d 100644 --- a/pymongo/settings_shared.py +++ b/pymongo/settings_shared.py @@ -18,8 +18,7 @@ import threading import traceback -from collections.abc import Callable, Collection -from typing import Any, Generic, Optional, TypeVar, Union +from typing import TYPE_CHECKING, Any, Generic, TypeVar from bson.objectid import ObjectId from pymongo import common @@ -29,6 +28,9 @@ from pymongo.server_description import ServerDescription from pymongo.topology_description import TOPOLOGY_TYPE, _ServerSelector +if TYPE_CHECKING: + from collections.abc import Callable, Collection + _PoolClassType = TypeVar("_PoolClassType") _MonitorClassType = TypeVar("_MonitorClassType") @@ -38,23 +40,23 @@ def __init__( self, pool_class: _PoolClassType, monitor_class: _MonitorClassType, - seeds: Optional[Collection[tuple[str, int]]] = None, - replica_set_name: Optional[str] = None, - pool_options: Optional[PoolOptions] = None, - condition_class: Optional[type[threading.Condition]] = None, + seeds: Collection[tuple[str, int]] | None = None, + replica_set_name: str | None = None, + pool_options: PoolOptions | None = None, + condition_class: type[threading.Condition] | None = None, local_threshold_ms: int = LOCAL_THRESHOLD_MS, server_selection_timeout: int = SERVER_SELECTION_TIMEOUT, heartbeat_frequency: int = common.HEARTBEAT_FREQUENCY, - server_selector: Optional[_ServerSelector] = None, - fqdn: Optional[str] = None, - direct_connection: Optional[bool] = False, - load_balanced: Optional[bool] = None, + server_selector: _ServerSelector | None = None, + fqdn: str | None = None, + direct_connection: bool | None = False, + load_balanced: bool | None = None, srv_service_name: str = common.SRV_SERVICE_NAME, srv_max_hosts: int = 0, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, server_monitoring_mode: str = common.SERVER_MONITORING_MODE, - topology_id: Optional[ObjectId] = None, + topology_id: ObjectId | None = None, ): """Represent MongoClient's configuration. @@ -96,7 +98,7 @@ def seeds(self) -> Collection[tuple[str, int]]: return self._seeds @property - def replica_set_name(self) -> Optional[str]: + def replica_set_name(self) -> str | None: return self._replica_set_name @property @@ -124,7 +126,7 @@ def server_selection_timeout(self) -> int: return self._server_selection_timeout @property - def server_selector(self) -> Optional[_ServerSelector]: + def server_selector(self) -> _ServerSelector | None: return self._server_selector @property @@ -132,11 +134,11 @@ def heartbeat_frequency(self) -> int: return self._heartbeat_frequency @property - def fqdn(self) -> Optional[str]: + def fqdn(self) -> str | None: return self._fqdn @property - def direct(self) -> Optional[bool]: + def direct(self) -> bool | None: """Connect directly to a single server, or use a set of servers? True if there is one seed and no replica_set_name. @@ -144,7 +146,7 @@ def direct(self) -> Optional[bool]: return self._direct @property - def load_balanced(self) -> Optional[bool]: + def load_balanced(self) -> bool | None: """True if the client was configured to connect to a load balancer.""" return self._load_balanced @@ -159,12 +161,12 @@ def srv_max_hosts(self) -> int: return self._srv_max_hosts @property - def srv_allowed_hosts_suffix(self) -> Optional[str]: + def srv_allowed_hosts_suffix(self) -> str | None: """The srvAllowedHostsSuffix.""" return self._srv_allowed_hosts_suffix @property - def srv_host_validator(self) -> Optional[Callable[[str], bool]]: + def srv_host_validator(self) -> Callable[[str], bool] | None: """The srv_host_validator callback.""" return self._srv_host_validator @@ -183,6 +185,6 @@ def get_topology_type(self) -> int: else: return TOPOLOGY_TYPE.Unknown - def get_server_descriptions(self) -> dict[Union[tuple[str, int], Any], ServerDescription]: + def get_server_descriptions(self) -> dict[tuple[str, int] | Any, ServerDescription]: """Initial dict of (address, ServerDescription) for all seeds.""" return {address: ServerDescription(address) for address in self.seeds} diff --git a/pymongo/socket_checker.py b/pymongo/socket_checker.py index 8424bf5062..1f81acabe7 100644 --- a/pymongo/socket_checker.py +++ b/pymongo/socket_checker.py @@ -18,30 +18,30 @@ import errno import select -from typing import Any, Optional, cast +from typing import Any, cast _HAVE_POLL = hasattr(select, "poll") _SelectError = getattr(select, "error", OSError) -def _errno_from_exception(exc: BaseException) -> Optional[int]: +def _errno_from_exception(exc: BaseException) -> int | None: if hasattr(exc, "errno"): - return cast(int, exc.errno) + return cast("int", exc.errno) if exc.args: - return cast(int, exc.args[0]) + return cast("int", exc.args[0]) return None class SocketChecker: def __init__(self) -> None: - self._poller: Optional[select.poll] + self._poller: select.poll | None if _HAVE_POLL: self._poller = select.poll() else: self._poller = None def select( - self, sock: Any, read: bool = False, write: bool = False, timeout: Optional[float] = 0 + self, sock: Any, read: bool = False, write: bool = False, timeout: float | None = 0 ) -> bool: """Select for reads or writes with a timeout in seconds (or None). diff --git a/pymongo/ssl_support.py b/pymongo/ssl_support.py index d505f8df27..4a95420c89 100644 --- a/pymongo/ssl_support.py +++ b/pymongo/ssl_support.py @@ -18,12 +18,14 @@ import os import sys -import types import warnings -from typing import Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo.errors import ConfigurationError +if TYPE_CHECKING: + import types + HAVE_SSL = True HAVE_PYSSL = True @@ -90,15 +92,15 @@ def _has_sni(is_sync: bool) -> bool: return _ssl.HAS_SNI def get_ssl_context( - certfile: Optional[str], - passphrase: Optional[str], - ca_certs: Optional[str], - crlfile: Optional[str], + certfile: str | None, + passphrase: str | None, + ca_certs: str | None, + crlfile: str | None, allow_invalid_certificates: bool, allow_invalid_hostnames: bool, disable_ocsp_endpoint_check: bool, is_sync: bool, - ) -> Union[_pyssl.SSLContext, _ssl.SSLContext]: # type: ignore[name-defined] + ) -> _pyssl.SSLContext | _ssl.SSLContext: # type: ignore[name-defined] """Create and return an SSLContext object.""" if is_sync and HAVE_PYSSL: ssl: types.ModuleType = _pyssl diff --git a/pymongo/synchronous/_kms_connect.py b/pymongo/synchronous/_kms_connect.py index 78d8119557..c9cf5acf4c 100644 --- a/pymongo/synchronous/_kms_connect.py +++ b/pymongo/synchronous/_kms_connect.py @@ -25,7 +25,7 @@ import inspect import socket import ssl -from typing import TYPE_CHECKING, Any, Optional, Union, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot from pymongo._kms_connect_shared import ( @@ -36,7 +36,6 @@ from pymongo.common import CONNECT_TIMEOUT from pymongo.errors import ConfigurationError from pymongo.helpers_shared import _get_timeout_details -from pymongo.pool_options import PoolOptions from pymongo.pool_shared import ( _close_late_socket, _configured_socket, @@ -45,6 +44,7 @@ ) if TYPE_CHECKING: + from pymongo.pool_options import PoolOptions from pymongo.pyopenssl_context import _sslConn from pymongo.typings import _Address @@ -57,9 +57,9 @@ def _connect_kms( address: _Address, opts: PoolOptions, - kms_connect_callback: Optional[KMSConnectCallback], + kms_connect_callback: KMSConnectCallback | None, timeout: float, -) -> Union[socket.socket, _sslConn]: +) -> socket.socket | _sslConn: """Connect to a KMS host and perform the TLS handshake over the socket. Uses ``kms_connect_callback`` when one is provided, otherwise connects @@ -85,7 +85,7 @@ def _connect_kms( ) # Any: the sync version's callback returns a plain socket. result: Any = kms_connect_callback( - KMSConnectContext(host=address[0], port=cast(int, address[1]), timeout=timeout) + KMSConnectContext(host=address[0], port=cast("int", address[1]), timeout=timeout) ) remaining = _csot.remaining() if remaining is None or _IS_SYNC: @@ -102,11 +102,11 @@ def _connect_kms( except asyncio.CancelledError: task.add_done_callback(_close_late_socket) raise - except asyncio.TimeoutError: + except TimeoutError: task.add_done_callback(_close_late_socket) _raise_connection_failure( address, - socket.timeout("timed out"), + TimeoutError("timed out"), timeout_details=_get_timeout_details(opts), ) if not isinstance(sock, socket.socket) or isinstance(sock, ssl.SSLSocket): diff --git a/pymongo/synchronous/aggregation.py b/pymongo/synchronous/aggregation.py index df49bbfbdd..3c81078eff 100644 --- a/pymongo/synchronous/aggregation.py +++ b/pymongo/synchronous/aggregation.py @@ -16,8 +16,7 @@ from __future__ import annotations -from collections.abc import Callable, Mapping, MutableMapping -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo import common from pymongo.collation import validate_collation_or_none @@ -25,6 +24,8 @@ from pymongo.read_preferences import ReadPreference, _AggWritePref if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping + from pymongo.read_preferences import _ServerMode from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection @@ -47,13 +48,13 @@ class _AggregationCommand: def __init__( self, - target: Union[Database[Any], Collection[Any]], + target: Database[Any] | Collection[Any], cursor_class: type[CommandCursor[Any]], pipeline: _Pipeline, options: MutableMapping[str, Any], - let: Optional[Mapping[str, Any]] = None, - user_fields: Optional[MutableMapping[str, Any]] = None, - result_processor: Optional[Callable[[Mapping[str, Any]], None]] = None, + let: Mapping[str, Any] | None = None, + user_fields: MutableMapping[str, Any] | None = None, + result_processor: Callable[[Mapping[str, Any]], None] | None = None, comment: Any = None, ) -> None: if "explain" in options: @@ -103,10 +104,10 @@ def __init__( self._collation = validate_collation_or_none(options.pop("collation", None)) self._max_await_time_ms = options.pop("maxAwaitTimeMS", None) - self._write_preference: Optional[_AggWritePref] = None + self._write_preference: _AggWritePref | None = None @property - def _aggregation_target(self) -> Union[str, int]: + def _aggregation_target(self) -> str | int: """The argument to pass to the aggregate command.""" raise NotImplementedError @@ -124,9 +125,7 @@ def _database(self) -> Database[Any]: """The database against which the aggregation command is run.""" raise NotImplementedError - def get_read_preference( - self, session: Optional[ClientSession] - ) -> Union[_AggWritePref, _ServerMode]: + def get_read_preference(self, session: ClientSession | None) -> _AggWritePref | _ServerMode: if self._write_preference: return self._write_preference pref = self._target._read_preference_for(session) @@ -136,7 +135,7 @@ def get_read_preference( def get_cursor( self, - session: Optional[ClientSession], + session: ClientSession | None, server: Server, conn: Connection, read_preference: _ServerMode, diff --git a/pymongo/synchronous/auth.py b/pymongo/synchronous/auth.py index e0b24ca4e2..1fc037c47b 100644 --- a/pymongo/synchronous/auth.py +++ b/pymongo/synchronous/auth.py @@ -21,7 +21,6 @@ import hmac import socket from base64 import standard_b64decode, standard_b64encode -from collections.abc import Callable, Mapping from typing import ( TYPE_CHECKING, Any, @@ -49,6 +48,8 @@ from pymongo.synchronous.helpers import _getaddrinfo if TYPE_CHECKING: + from collections.abc import Callable, Mapping + from pymongo.synchronous.pool import Connection HAVE_KERBEROS = True diff --git a/pymongo/synchronous/auth_aws.py b/pymongo/synchronous/auth_aws.py index 777e0620f5..be8011c4f6 100644 --- a/pymongo/synchronous/auth_aws.py +++ b/pymongo/synchronous/auth_aws.py @@ -16,7 +16,6 @@ from __future__ import annotations -from collections.abc import Mapping from typing import TYPE_CHECKING, Any import bson @@ -24,6 +23,8 @@ from pymongo.errors import ConfigurationError, OperationFailure if TYPE_CHECKING: + from collections.abc import Mapping + from bson.typings import _ReadableBuffer from pymongo.auth_shared import MongoCredential from pymongo.synchronous.pool import Connection diff --git a/pymongo/synchronous/auth_oidc.py b/pymongo/synchronous/auth_oidc.py index 7d242bc326..299b3eb17b 100644 --- a/pymongo/synchronous/auth_oidc.py +++ b/pymongo/synchronous/auth_oidc.py @@ -17,11 +17,9 @@ from __future__ import annotations import asyncio -import threading import time -from collections.abc import Mapping, MutableMapping from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any import bson from pymongo._csot import remaining @@ -41,6 +39,9 @@ from pymongo.lock import Lock, _create_lock if TYPE_CHECKING: + import threading + from collections.abc import Mapping, MutableMapping + from pymongo.auth_shared import MongoCredential from pymongo.synchronous.pool import Connection @@ -54,7 +55,7 @@ class _OIDCAuthenticator(_OIDCAuthenticatorBase): else: lock: threading.Lock = field(default_factory=_create_lock) # type: ignore[assignment, no-redef] - def reauthenticate(self, conn: Connection) -> Optional[Mapping[str, Any]]: + def reauthenticate(self, conn: Connection) -> Mapping[str, Any] | None: """Handle a reauthenticate from the server.""" # Invalidate the token for the connection. self._invalidate(conn.oidc_token_gen_id) @@ -63,7 +64,7 @@ def reauthenticate(self, conn: Connection) -> Optional[Mapping[str, Any]]: return self._authenticate_machine(conn) return self._authenticate_human(conn) - def authenticate(self, conn: Connection) -> Optional[Mapping[str, Any]]: + def authenticate(self, conn: Connection) -> Mapping[str, Any] | None: """Handle an initial authenticate request.""" # First handle speculative auth. # If it succeeded, we are done. @@ -95,7 +96,7 @@ def _authenticate_machine(self, conn: Connection) -> Mapping[str, Any]: raise return self._sasl_start_jwt(conn) - def _authenticate_human(self, conn: Connection) -> Optional[Mapping[str, Any]]: + def _authenticate_human(self, conn: Connection) -> Mapping[str, Any] | None: # If we have a cached access token, try a JwtStepRequest. # authentication fails with error code 18, invalidate the access token, # and try to authenticate again. If authentication fails for any other @@ -128,9 +129,9 @@ def _authenticate_human(self, conn: Connection) -> Optional[Mapping[str, Any]]: # Attempt to authenticate with a JwtStepRequest. return self._sasl_continue_jwt(conn, start_resp) - def _get_access_token(self) -> Optional[str]: + def _get_access_token(self) -> str | None: properties = self.properties - cb: Union[None, OIDCCallback] + cb: OIDCCallback | None resp: OIDCCallbackResult is_human = properties.human_callback is not None @@ -180,7 +181,7 @@ def _get_access_token(self) -> Optional[str]: else: resp = cb.fetch(context) if not isinstance(resp, OIDCCallbackResult): - raise ValueError( + raise TypeError( f"Callback result must be of type OIDCCallbackResult, not {type(resp)}" ) self.refresh_token = resp.refresh_token @@ -219,7 +220,7 @@ def _sasl_start_jwt(self, conn: Connection) -> Mapping[str, Any]: def _authenticate_oidc( credentials: MongoCredential, conn: Connection, reauthenticate: bool -) -> Optional[Mapping[str, Any]]: +) -> Mapping[str, Any] | None: """Authenticate using MONGODB-OIDC.""" authenticator = _get_authenticator(credentials, conn.address, _OIDCAuthenticator) if reauthenticate: diff --git a/pymongo/synchronous/bulk.py b/pymongo/synchronous/bulk.py index 02a728d37f..b3b54abbe7 100644 --- a/pymongo/synchronous/bulk.py +++ b/pymongo/synchronous/bulk.py @@ -20,13 +20,10 @@ from __future__ import annotations import copy -from collections.abc import Iterator, Mapping, MutableMapping from itertools import islice from typing import ( TYPE_CHECKING, Any, - Optional, - Union, ) from pymongo import _csot @@ -51,7 +48,6 @@ _EncryptedBulkWriteContext, ) from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.command_runner import ( run_bulk_write_command, ) @@ -59,6 +55,9 @@ from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, MutableMapping + + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection @@ -101,7 +100,7 @@ def unack_write( max_doc_size: int, docs: list[Mapping[str, Any]], client: MongoClient[Any], - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: """Send an unacknowledged batch write command.""" # Historically the STARTED log omits the documents while the published # CommandStartedEvent includes them, so log ``cmd`` but publish a copy @@ -122,7 +121,7 @@ def unack_write( def _execute_batch_unack( self, - bwc: Union[_BulkWriteContext, _EncryptedBulkWriteContext], + bwc: _BulkWriteContext | _EncryptedBulkWriteContext, cmd: dict[str, Any], ops: list[Mapping[str, Any]], client: MongoClient[Any], @@ -149,7 +148,7 @@ def _execute_batch_unack( def _execute_batch( self, - bwc: Union[_BulkWriteContext, _EncryptedBulkWriteContext], + bwc: _BulkWriteContext | _EncryptedBulkWriteContext, cmd: dict[str, Any], ops: list[Mapping[str, Any]], client: MongoClient[Any], @@ -173,12 +172,12 @@ def _execute_command( self, generator: Iterator[Any], write_concern: WriteConcern, - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, - op_id: Optional[int], + op_id: int | None, retryable: bool, full_result: MutableMapping[str, Any], - final_write_concern: Optional[WriteConcern] = None, + final_write_concern: WriteConcern | None = None, ) -> None: db_name = self.collection.database.name client = self.collection.database.client @@ -276,7 +275,7 @@ def execute_command( self, generator: Iterator[Any], write_concern: WriteConcern, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> dict[str, Any]: """Execute using write commands.""" @@ -295,7 +294,7 @@ def execute_command( op_id = _generate_op_id_or_none(client._event_listeners) def retryable_bulk( - session: Optional[ClientSession], conn: Connection, retryable: bool + session: ClientSession | None, conn: Connection, retryable: bool ) -> None: self._execute_command( generator, @@ -423,7 +422,7 @@ def execute_no_results( def execute( self, write_concern: WriteConcern, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> Any: """Execute operations.""" diff --git a/pymongo/synchronous/change_stream.py b/pymongo/synchronous/change_stream.py index 0afaffe659..3336b4f6e6 100644 --- a/pymongo/synchronous/change_stream.py +++ b/pymongo/synchronous/change_stream.py @@ -16,7 +16,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING from bson import _bson_to_dict from pymongo import _csot @@ -42,6 +42,8 @@ _IS_SYNC = True if TYPE_CHECKING: + from types import TracebackType + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.database import Database @@ -60,13 +62,13 @@ class ChangeStream(_AgnosticChangeStream[_DocumentType, "MongoClient[_DocumentTy .. seealso:: The MongoDB documentation on `changeStreams `_. """ - _session: Optional[ClientSession] + _session: ClientSession | None def _initialize_cursor(self) -> None: # Initialize cursor. self._cursor = self._create_cursor() - def _run_aggregation_cmd(self, session: Optional[ClientSession]) -> CommandCursor: # type: ignore[type-arg] + def _run_aggregation_cmd(self, session: ClientSession | None) -> CommandCursor: # type: ignore[type-arg] """Run the full aggregation pipeline for this ChangeStream and return the corresponding CommandCursor. """ @@ -148,7 +150,7 @@ def next(self) -> _DocumentType: __next__ = next @_csot.apply - def try_next(self) -> Optional[_DocumentType]: + def try_next(self) -> _DocumentType | None: """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting @@ -246,7 +248,12 @@ def try_next(self) -> Optional[_DocumentType]: def __enter__(self) -> ChangeStream[_DocumentType]: return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: self.close() diff --git a/pymongo/synchronous/client_bulk.py b/pymongo/synchronous/client_bulk.py index 3af8fdf6b9..097df34f89 100644 --- a/pymongo/synchronous/client_bulk.py +++ b/pymongo/synchronous/client_bulk.py @@ -20,18 +20,14 @@ from __future__ import annotations import copy -from collections.abc import Mapping, MutableMapping from itertools import islice from typing import ( TYPE_CHECKING, Any, - Optional, - Union, ) from pymongo import _csot from pymongo._telemetry import _generate_op_id_or_none -from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.command_cursor import CommandCursor from pymongo.synchronous.command_runner import ( @@ -41,8 +37,12 @@ from pymongo.synchronous.helpers import _handle_reauth if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping + + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection + from pymongo.write_concern import WriteConcern from pymongo._client_bulk_shared import ( _AgnosticClientBulkBase, _merge_command, @@ -70,7 +70,6 @@ InsertOneResult, UpdateResult, ) -from pymongo.write_concern import WriteConcern _IS_SYNC = True @@ -86,7 +85,7 @@ def write_command( bwc: _ClientBulkWriteContext, cmd: MutableMapping[str, Any], request_id: int, - msg: Union[bytes, dict[str, Any]], + msg: bytes | dict[str, Any], op_docs: list[Mapping[str, Any]], ns_docs: list[Mapping[str, Any]], client: MongoClient[Any], @@ -117,7 +116,7 @@ def unack_write( op_docs: list[Mapping[str, Any]], ns_docs: list[Mapping[str, Any]], client: MongoClient[Any], - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: """Send an unacknowledged client-level batch write command.""" # Historically the STARTED log omits the ops/nsInfo while the published # CommandStartedEvent includes them, so log ``cmd`` but publish a copy @@ -171,7 +170,7 @@ def _process_results_cursor( full_result: MutableMapping[str, Any], result: MutableMapping[str, Any], conn: Connection, - session: Optional[ClientSession], + session: ClientSession | None, ) -> None: """Internal helper for processing the server reply command cursor.""" if result.get("cursor"): @@ -221,12 +220,12 @@ def _process_results_cursor( def _execute_command( self, write_concern: WriteConcern, - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, - op_id: Optional[int], + op_id: int | None, retryable: bool, full_result: MutableMapping[str, Any], - final_write_concern: Optional[WriteConcern] = None, + final_write_concern: WriteConcern | None = None, ) -> None: """Internal helper for executing batches of bulkWrite commands.""" db_name = "admin" @@ -359,7 +358,7 @@ def _execute_command( def execute_command( self, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> MutableMapping[str, Any]: """Execute commands with w=1 WriteConcern.""" @@ -380,7 +379,7 @@ def execute_command( op_id = _generate_op_id_or_none(self.client._event_listeners) def retryable_bulk( - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, retryable: bool, ) -> None: @@ -471,7 +470,7 @@ def execute_no_results( def execute( self, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> Any: """Execute operations.""" diff --git a/pymongo/synchronous/client_session.py b/pymongo/synchronous/client_session.py index 53631139ed..fd24dbf230 100644 --- a/pymongo/synchronous/client_session.py +++ b/pymongo/synchronous/client_session.py @@ -137,13 +137,11 @@ import random import time -from collections.abc import Callable -from contextlib import AbstractContextManager from contextvars import ContextVar, Token from typing import ( TYPE_CHECKING, Any, - Optional, + Self, TypeVar, ) @@ -169,20 +167,22 @@ PyMongoError, WTimeoutError, ) -from pymongo.read_concern import ReadConcern -from pymongo.read_preferences import _ServerMode from pymongo.synchronous.cursor_base import _ConnectionManager from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Callable + from contextlib import AbstractContextManager from types import TracebackType + from pymongo.read_concern import ReadConcern + from pymongo.read_preferences import _ServerMode from pymongo.synchronous.mongo_client import MongoClient from pymongo.synchronous.pool import Connection _IS_SYNC = True -_SESSION: ContextVar[Optional[ClientSession]] = ContextVar("SESSION", default=None) +_SESSION: ContextVar[ClientSession | None] = ContextVar("SESSION", default=None) class _BoundSessionContext: @@ -190,14 +190,19 @@ class _BoundSessionContext: def __init__(self, session: ClientSession, end_session: bool) -> None: self._session = session - self._session_token: Optional[Token[ClientSession]] = None + self._session_token: Token[ClientSession] | None = None self._end_session = end_session def __enter__(self) -> ClientSession: self._session_token = _SESSION.set(self._session) # type: ignore[assignment] return self._session - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: if self._session_token: _SESSION.reset(self._session_token) # type: ignore[arg-type] self._session_token = None @@ -211,14 +216,14 @@ class _TransactionContext: def __init__(self, session: ClientSession): self.__session = session - def __enter__(self) -> _TransactionContext: + def __enter__(self) -> Self: return self def __exit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: if self.__session.in_transaction: if exc_val is None: @@ -231,7 +236,7 @@ class _Transaction(_TransactionBase["Connection"]): """Internal class to hold transaction information in a ClientSession.""" _conn_mgr_cls = _ConnectionManager - conn_mgr: Optional[_ConnectionManager] + conn_mgr: _ConnectionManager | None def unpin(self) -> None: self.pinned_address = None @@ -290,19 +295,24 @@ def _end_session(self, lock: bool) -> None: self._client._return_server_session(self._server_session) self._server_session = None - def __enter__(self) -> ClientSession: + def __enter__(self) -> Self: return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: self._end_session(lock=True) def with_transaction( self, callback: Callable[[ClientSession], _T], - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, - max_commit_time_ms: Optional[int] = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, + max_commit_time_ms: int | None = None, ) -> _T: """Execute a callback in a transaction. @@ -398,7 +408,7 @@ def callback(session, custom_arg, custom_kwarg=None): """ start_time = time.monotonic() retry = 0 - last_error: Optional[BaseException] = None + last_error: BaseException | None = None while True: if retry: # Implement exponential backoff on retry. jitter = random.random() # noqa: S311 @@ -454,10 +464,10 @@ def callback(session, custom_arg, custom_kwarg=None): def start_transaction( self, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - read_preference: Optional[_ServerMode] = None, - max_commit_time_ms: Optional[int] = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + read_preference: _ServerMode | None = None, + max_commit_time_ms: int | None = None, ) -> AbstractContextManager[Any]: """Start a multi-statement transaction. @@ -570,7 +580,7 @@ def _finish_transaction_with_retry(self, command_name: str) -> dict[str, Any]: """ def func( - _session: Optional[ClientSession], conn: Connection, _retryable: bool + _session: ClientSession | None, conn: Connection, _retryable: bool ) -> dict[str, Any]: return self._finish_transaction(conn, command_name) diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index eccd7c57b9..34b00cec50 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -18,22 +18,12 @@ import warnings from collections import abc -from collections.abc import ( - Callable, - Iterable, - Iterator, - Mapping, - MutableMapping, - Sequence, -) from typing import ( TYPE_CHECKING, Any, Generic, NoReturn, - Optional, TypeVar, - Union, cast, overload, ) @@ -42,7 +32,6 @@ from bson.objectid import ObjectId from bson.raw_bson import RawBSONDocument from bson.son import SON -from bson.timestamp import Timestamp from pymongo import ASCENDING, _csot, common, helpers_shared, message from pymongo.collation import validate_collation_or_none from pymongo.common import _ecoc_coll_name, _esc_coll_name @@ -100,14 +89,14 @@ _FIND_AND_MODIFY_DOC_FIELDS = {"value": 1} -_WriteOp = Union[ - InsertOne[_DocumentType], - DeleteOne, - DeleteMany, - ReplaceOne[_DocumentType], - UpdateOne, - UpdateMany, -] +_WriteOp = ( + InsertOne[_DocumentType] + | DeleteOne + | DeleteMany + | ReplaceOne[_DocumentType] + | UpdateOne + | UpdateMany +) class ReturnDocument: @@ -125,7 +114,17 @@ class ReturnDocument: if TYPE_CHECKING: + from collections.abc import ( + Callable, + Iterable, + Iterator, + Mapping, + MutableMapping, + Sequence, + ) + import bson + from bson.timestamp import Timestamp from pymongo.collation import Collation from pymongo.read_concern import ReadConcern from pymongo.synchronous.aggregation import _AggregationCommand @@ -142,12 +141,12 @@ def __init__( self, database: Database[_DocumentType], name: str, - create: Optional[bool] = False, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, - session: Optional[ClientSession] = None, + create: bool | None = False, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, + session: ClientSession | None = None, **kwargs: Any, ) -> None: """Get / create a Mongo collection. @@ -297,12 +296,12 @@ def __getitem__(self, name: str) -> Collection[_DocumentType]: def __repr__(self) -> str: return f"{type(self).__name__}({self._database!r}, {self._name!r})" - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Collection): return self._database == other.database and self._name == other.name return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -339,26 +338,26 @@ def database(self) -> Database[_DocumentType]: def with_options( self, codec_options: None = None, - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> Collection[_DocumentType]: ... @overload def with_options( self, codec_options: bson.CodecOptions[_DocumentTypeArg], - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> Collection[_DocumentTypeArg]: ... def with_options( self, - codec_options: Optional[bson.CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: bson.CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> Collection[_DocumentType] | Collection[_DocumentTypeArg]: """Get a clone of this collection changing the specified settings. @@ -423,18 +422,18 @@ def __call__(self, *args: Any, **kwargs: Any) -> NoReturn: def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[ClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: ClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> CollectionChangeStream[_DocumentType]: """Watch changes on this collection. @@ -566,16 +565,16 @@ def _command( self, conn: Connection, command: MutableMapping[str, Any], - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[CodecOptions[Mapping[str, Any]]] = None, + read_preference: _ServerMode | None = None, + codec_options: CodecOptions[Mapping[str, Any]] | None = None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, - collation: Optional[_CollationIn] = None, - session: Optional[ClientSession] = None, + allowable_errors: Sequence[str | int] | None = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, + collation: _CollationIn | None = None, + session: ClientSession | None = None, retryable_write: bool = False, - user_fields: Optional[Any] = None, + user_fields: Any | None = None, ) -> Mapping[str, Any]: """Internal command helper. @@ -624,9 +623,9 @@ def _create_helper( self, name: str, options: MutableMapping[str, Any], - collation: Optional[_CollationIn], - session: Optional[ClientSession], - encrypted_fields: Optional[Mapping[str, Any]] = None, + collation: _CollationIn | None, + session: ClientSession | None, + encrypted_fields: Mapping[str, Any] | None = None, qev2_required: bool = False, ) -> None: """Sends a create command with the given options.""" @@ -639,9 +638,7 @@ def _create_helper( options["size"] = float(options["size"]) cmd.update(options) - def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool - ) -> None: + def inner(session: ClientSession | None, conn: Connection, _retryable_write: bool) -> None: if qev2_required and conn.max_wire_version < 21: raise ConfigurationError( "Driver support of Queryable Encryption is incompatible with server. " @@ -663,7 +660,7 @@ def inner( def _create( self, options: MutableMapping[str, Any], - session: Optional[ClientSession], + session: ClientSession | None, ) -> None: collation = validate_collation_or_none(options.pop("collation", None)) encrypted_fields = options.pop("encryptedFields", None) @@ -690,10 +687,10 @@ def bulk_write( self, requests: Sequence[_WriteOp[_DocumentType]], ordered: bool = True, - bypass_document_validation: Optional[bool] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, - let: Optional[Mapping[str, Any]] = None, + bypass_document_validation: bool | None = None, + session: ClientSession | None = None, + comment: Any | None = None, + let: Mapping[str, Any] | None = None, ) -> BulkWriteResult: """Send a batch of write operations to the server. @@ -788,10 +785,10 @@ def _insert_one( doc: Mapping[str, Any], ordered: bool, write_concern: WriteConcern, - op_id: Optional[int], - bypass_doc_val: Optional[bool], - session: Optional[ClientSession], - comment: Optional[Any] = None, + op_id: int | None, + bypass_doc_val: bool | None, + session: ClientSession | None, + comment: Any | None = None, ) -> Any: """Internal helper for inserting a single document.""" write_concern = write_concern or self.write_concern @@ -801,7 +798,7 @@ def _insert_one( command["comment"] = comment def _insert_command( - session: Optional[ClientSession], conn: Connection, retryable_write: bool + session: ClientSession | None, conn: Connection, retryable_write: bool ) -> None: if bypass_doc_val is not None: command["bypassDocumentValidation"] = bypass_doc_val @@ -828,10 +825,10 @@ def _insert_command( def insert_one( self, - document: Union[_DocumentType, RawBSONDocument], - bypass_document_validation: Optional[bool] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + document: _DocumentType | RawBSONDocument, + bypass_document_validation: bool | None = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> InsertOneResult: """Insert a single document. @@ -893,11 +890,11 @@ def insert_one( @_csot.apply def insert_many( self, - documents: Iterable[Union[_DocumentType, RawBSONDocument]], + documents: Iterable[_DocumentType | RawBSONDocument], ordered: bool = True, - bypass_document_validation: Optional[bool] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> InsertManyResult: """Insert an iterable of documents. @@ -969,22 +966,22 @@ def _update( self, conn: Connection, criteria: Mapping[str, Any], - document: Union[Mapping[str, Any], _Pipeline], + document: Mapping[str, Any] | _Pipeline, upsert: bool = False, multi: bool = False, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - bypass_doc_val: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, + bypass_doc_val: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, retryable_write: bool = False, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - ) -> Optional[Mapping[str, Any]]: + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, + ) -> Mapping[str, Any] | None: """Internal update / replace helper.""" validate_boolean("upsert", upsert) collation = validate_collation_or_none(collation) @@ -1060,27 +1057,27 @@ def _update( def _update_retryable( self, criteria: Mapping[str, Any], - document: Union[Mapping[str, Any], _Pipeline], + document: Mapping[str, Any] | _Pipeline, operation: str, upsert: bool = False, multi: bool = False, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - bypass_doc_val: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - ) -> Optional[Mapping[str, Any]]: + bypass_doc_val: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, + ) -> Mapping[str, Any] | None: """Internal update / replace helper.""" def _update( - session: Optional[ClientSession], conn: Connection, retryable_write: bool - ) -> Optional[Mapping[str, Any]]: + session: ClientSession | None, conn: Connection, retryable_write: bool + ) -> Mapping[str, Any] | None: return self._update( conn, criteria, @@ -1113,13 +1110,13 @@ def replace_one( filter: Mapping[str, Any], replacement: Mapping[str, Any], upsert: bool = False, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Replace a single document matching the filter. @@ -1219,16 +1216,16 @@ def replace_one( def update_one( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, upsert: bool = False, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - sort: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + sort: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Update a single document matching the filter. @@ -1338,15 +1335,15 @@ def update_one( def update_many( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], + update: Mapping[str, Any] | _Pipeline, upsert: bool = False, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - bypass_document_validation: Optional[bool] = None, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + bypass_document_validation: bool | None = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> UpdateResult: """Update one or more documents that match the filter. @@ -1437,9 +1434,9 @@ def update_many( def drop( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, - encrypted_fields: Optional[Mapping[str, Any]] = None, + session: ClientSession | None = None, + comment: Any | None = None, + encrypted_fields: Mapping[str, Any] | None = None, ) -> None: """Alias for :meth:`~pymongo.database.Database.drop_collection`. @@ -1483,15 +1480,15 @@ def _delete( conn: Connection, criteria: Mapping[str, Any], multi: bool, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, retryable_write: bool = False, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> Mapping[str, Any]: """Internal delete helper.""" common.validate_is_mapping("filter", criteria) @@ -1534,19 +1531,19 @@ def _delete_retryable( self, criteria: Mapping[str, Any], multi: bool, - write_concern: Optional[WriteConcern] = None, - op_id: Optional[int] = None, + write_concern: WriteConcern | None = None, + op_id: int | None = None, ordered: bool = True, - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> Mapping[str, Any]: """Internal delete helper.""" def _delete( - session: Optional[ClientSession], conn: Connection, retryable_write: bool + session: ClientSession | None, conn: Connection, retryable_write: bool ) -> Mapping[str, Any]: return self._delete( conn, @@ -1573,11 +1570,11 @@ def _delete( def delete_one( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> DeleteResult: """Delete a single document matching the filter. @@ -1638,11 +1635,11 @@ def delete_one( def delete_many( self, filter: Mapping[str, Any], - collation: Optional[_CollationIn] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + collation: _CollationIn | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, ) -> DeleteResult: """Delete one or more documents matching the filter. @@ -1701,8 +1698,8 @@ def delete_many( ) def find_one( - self, filter: Optional[Any] = None, *args: Any, **kwargs: Any - ) -> Optional[_DocumentType]: + self, filter: Any | None = None, *args: Any, **kwargs: Any + ) -> _DocumentType | None: """Get a single document from the database. All arguments to :meth:`find` are also valid arguments for @@ -1977,11 +1974,11 @@ def find_raw_batches(self, *args: Any, **kwargs: Any) -> RawBatchCursor[_Documen def _count_cmd( self, - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, cmd: dict[str, Any], - collation: Optional[Collation], + collation: Collation | None, ) -> int: """Internal count command helper.""" res = self._command( @@ -1998,11 +1995,11 @@ def _count_cmd( def _aggregate_one_result( self, conn: Connection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, cmd: dict[str, Any], - collation: Optional[_CollationIn], - session: Optional[ClientSession], - ) -> Optional[Mapping[str, Any]]: + collation: _CollationIn | None, + session: ClientSession | None, + ) -> Mapping[str, Any] | None: """Internal helper to run an aggregate that returns a single result.""" result = self._command( conn, @@ -2020,7 +2017,7 @@ def _aggregate_one_result( batch = result["cursor"]["firstBatch"] return batch[0] if batch else None - def estimated_document_count(self, comment: Optional[Any] = None, **kwargs: Any) -> int: + def estimated_document_count(self, comment: Any | None = None, **kwargs: Any) -> int: """Get an estimate of the number of documents in this collection using collection metadata. @@ -2053,10 +2050,10 @@ def estimated_document_count(self, comment: Optional[Any] = None, **kwargs: Any) kwargs["comment"] = comment def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> int: cmd: dict[str, Any] = {"count": self._name} cmd.update(kwargs) @@ -2067,8 +2064,8 @@ def _cmd( def count_documents( self, filter: Mapping[str, Any], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> int: """Count the number of documents in this collection. @@ -2139,10 +2136,10 @@ def count_documents( collation = validate_collation_or_none(kwargs.pop("collation", None)) def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> int: cmd: dict[str, Any] = {"aggregate": self._name, "pipeline": pipeline, "cursor": {}} cmd.update(kwargs) @@ -2156,10 +2153,10 @@ def _cmd( def _retryable_non_cursor_read( self, func: Callable[ - [Optional[ClientSession], Server, Connection, Optional[_ServerMode]], + [ClientSession | None, Server, Connection, _ServerMode | None], T, ], - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> T: """Non-cursor read helper to handle implicit session creation.""" @@ -2170,8 +2167,8 @@ def _retryable_non_cursor_read( def create_indexes( self, indexes: Sequence[IndexModel], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: """Create one or more indexes on this collection. @@ -2216,7 +2213,7 @@ def create_indexes( @_csot.apply def _create_indexes( - self, indexes: Sequence[IndexModel], session: Optional[ClientSession], **kwargs: Any + self, indexes: Sequence[IndexModel], session: ClientSession | None, **kwargs: Any ) -> list[str]: """Internal createIndexes helper. @@ -2230,7 +2227,7 @@ def _create_indexes( names = [] def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool + session: ClientSession | None, conn: Connection, _retryable_write: bool ) -> list[str]: def gen_indexes() -> Iterator[Mapping[str, Any]]: for index in indexes: @@ -2259,8 +2256,8 @@ def gen_indexes() -> Iterator[Mapping[str, Any]]: def create_index( self, keys: _IndexKeyHint, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> str: """Creates an index on this collection. @@ -2376,8 +2373,8 @@ def create_index( def drop_indexes( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Drops all indexes on this collection. @@ -2410,8 +2407,8 @@ def drop_indexes( def drop_index( self, index_or_name: _IndexKeyHint, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Drops the specified index on this collection. @@ -2459,8 +2456,8 @@ def drop_index( def _drop_index( self, index_or_name: _IndexKeyHint, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: name = index_or_name @@ -2475,9 +2472,7 @@ def _drop_index( if comment is not None: cmd["comment"] = comment - def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool - ) -> None: + def inner(session: ClientSession | None, conn: Connection, _retryable_write: bool) -> None: self._command( conn, cmd, @@ -2491,8 +2486,8 @@ def inner( def list_indexes( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> CommandCursor[MutableMapping[str, Any]]: """Get a cursor over the index documents for this collection. @@ -2529,18 +2524,18 @@ def list_indexes( def _list_indexes( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> CommandCursor[MutableMapping[str, Any]]: codec_options: CodecOptions[Mapping[str, Any]] = CodecOptions(SON) coll = cast( - Collection[MutableMapping[str, Any]], + "Collection[MutableMapping[str, Any]]", self.with_options(codec_options=codec_options, read_preference=ReadPreference.PRIMARY), ) read_pref = (session and session._txn_read_preference()) or ReadPreference.PRIMARY def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, @@ -2576,8 +2571,8 @@ def _cmd( def index_information( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> MutableMapping[str, Any]: """Get information on this collection's indexes. @@ -2618,9 +2613,9 @@ def index_information( def list_search_indexes( self, - name: Optional[str] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + name: str | None = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[Mapping[str, Any]]: """Return a cursor over search indexes for the current collection. @@ -2679,8 +2674,8 @@ def list_search_indexes( def create_search_index( self, - model: Union[Mapping[str, Any], SearchIndexModel], - session: Optional[ClientSession] = None, + model: Mapping[str, Any] | SearchIndexModel, + session: ClientSession | None = None, comment: Any = None, **kwargs: Any, ) -> str: @@ -2710,8 +2705,8 @@ def create_search_index( def create_search_indexes( self, models: list[SearchIndexModel], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: """Create multiple search indexes for the current collection. @@ -2734,8 +2729,8 @@ def create_search_indexes( def _create_search_indexes( self, models: list[SearchIndexModel], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: if comment is not None: @@ -2753,7 +2748,7 @@ def gen_indexes() -> Iterator[Mapping[str, Any]]: cmd.update(kwargs) def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool + session: ClientSession | None, conn: Connection, _retryable_write: bool ) -> list[str]: resp = self._command( conn, @@ -2771,8 +2766,8 @@ def inner( def drop_search_index( self, name: str, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Delete a search index by index name. @@ -2794,9 +2789,7 @@ def drop_search_index( if comment is not None: cmd["comment"] = comment - def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool - ) -> None: + def inner(session: ClientSession | None, conn: Connection, _retryable_write: bool) -> None: self._command( conn, cmd, @@ -2812,8 +2805,8 @@ def update_search_index( self, name: str, definition: Mapping[str, Any], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> None: """Update a search index by replacing the existing index definition with the provided definition. @@ -2836,9 +2829,7 @@ def update_search_index( if comment is not None: cmd["comment"] = comment - def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool - ) -> None: + def inner(session: ClientSession | None, conn: Connection, _retryable_write: bool) -> None: self._command( conn, cmd, @@ -2852,8 +2843,8 @@ def inner( def options( self, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, ) -> MutableMapping[str, Any]: """Get the options set on this collection. @@ -2900,9 +2891,9 @@ def _aggregate( aggregation_command: type[_AggregationCommand], pipeline: _Pipeline, cursor_class: type[CommandCursor], # type: ignore[type-arg] - session: Optional[ClientSession], - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[_DocumentType]: if comment is not None: @@ -2928,9 +2919,9 @@ def _aggregate( def aggregate( self, pipeline: _Pipeline, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[_DocumentType]: """Perform an aggregation using the aggregation framework on this @@ -3032,8 +3023,8 @@ def aggregate( def aggregate_raw_batches( self, pipeline: _Pipeline, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> RawBatchCursor[_DocumentType]: """Perform an aggregation and retrieve batches of raw BSON. @@ -3066,7 +3057,7 @@ def aggregate_raw_batches( kwargs["comment"] = comment with self._database.client._tmp_session(session) as s: return cast( - RawBatchCursor[_DocumentType], + "RawBatchCursor[_DocumentType]", self._aggregate( _CollectionRawAggregationCommand, pipeline, @@ -3080,8 +3071,8 @@ def aggregate_raw_batches( def rename( self, new_name: str, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> MutableMapping[str, Any]: """Rename this collection. @@ -3131,7 +3122,7 @@ def rename( client = self._database.client def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool + session: ClientSession | None, conn: Connection, _retryable_write: bool ) -> MutableMapping[str, Any]: return conn.command( "admin", @@ -3147,10 +3138,10 @@ def inner( def distinct( self, key: str, - filter: Optional[Mapping[str, Any]] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, - hint: Optional[_IndexKeyHint] = None, + filter: Mapping[str, Any] | None = None, + session: ClientSession | None = None, + comment: Any | None = None, + hint: _IndexKeyHint | None = None, **kwargs: Any, ) -> list[Any]: """Get a list of distinct values for `key` among all documents @@ -3206,10 +3197,10 @@ def distinct( hint = helpers_shared._index_document(hint) def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, ) -> list: # type: ignore[type-arg] cmd = {"distinct": self._name, "key": key} cmd.update(kwargs) @@ -3234,20 +3225,20 @@ def _cmd( def _find_and_modify( self, filter: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]], - sort: Optional[_IndexList], - upsert: Optional[bool] = None, + projection: Mapping[str, Any] | Iterable[str] | None, + sort: _IndexList | None, + upsert: bool | None = None, return_document: bool = ReturnDocument.BEFORE, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, **kwargs: Any, ) -> Any: """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isinstance(return_document, bool): - raise ValueError( + raise TypeError( f"return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not {type(return_document)}" ) collation = validate_collation_or_none(kwargs.pop("collation", None)) @@ -3257,7 +3248,7 @@ def _find_and_modify( write_concern = self._write_concern_for_cmd(kwargs, session) def _find_and_modify_helper( - session: Optional[ClientSession], conn: Connection, retryable_write: bool + session: ClientSession | None, conn: Connection, retryable_write: bool ) -> Any: cmd = {"findAndModify": self._name, "query": filter, "new": return_document} if let is not None: @@ -3304,14 +3295,14 @@ def _find_and_modify_helper( def find_one_and_delete( self, filter: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and deletes it, returning the document. >>> db.test.count_documents({'x': 1}) @@ -3398,16 +3389,16 @@ def find_one_and_replace( self, filter: Mapping[str, Any], replacement: Mapping[str, Any], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, upsert: bool = False, return_document: bool = ReturnDocument.BEFORE, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and replaces it, returning either the original or the replaced document. @@ -3516,18 +3507,18 @@ def find_one_and_replace( def find_one_and_update( self, filter: Mapping[str, Any], - update: Union[Mapping[str, Any], _Pipeline], - projection: Optional[Union[Mapping[str, Any], Iterable[str]]] = None, - sort: Optional[_IndexList] = None, + update: Mapping[str, Any] | _Pipeline, + projection: Mapping[str, Any] | Iterable[str] | None = None, + sort: _IndexList | None = None, upsert: bool = False, return_document: bool = ReturnDocument.BEFORE, - array_filters: Optional[Sequence[Mapping[str, Any]]] = None, - hint: Optional[_IndexKeyHint] = None, - session: Optional[ClientSession] = None, - let: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + array_filters: Sequence[Mapping[str, Any]] | None = None, + hint: _IndexKeyHint | None = None, + session: ClientSession | None = None, + let: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Finds a single document and updates it, returning either the original or the updated document. diff --git a/pymongo/synchronous/command_cursor.py b/pymongo/synchronous/command_cursor.py index d7fc3e39ca..43a8ce73ee 100644 --- a/pymongo/synchronous/command_cursor.py +++ b/pymongo/synchronous/command_cursor.py @@ -17,12 +17,10 @@ from __future__ import annotations from collections import deque -from collections.abc import Iterator, Mapping from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, ) from bson import CodecOptions, _convert_raw_document_lists_to_streams @@ -34,6 +32,8 @@ from pymongo.typings import _Address, _DocumentType if TYPE_CHECKING: + from collections.abc import Iterator, Mapping + from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.collection import Collection from pymongo.synchronous.pool import Connection @@ -161,7 +161,7 @@ def next(self) -> _DocumentType: def __next__(self) -> _DocumentType: return self.next() - def _try_next(self, get_more_allowed: bool) -> Optional[_DocumentType]: + def _try_next(self, get_more_allowed: bool) -> _DocumentType | None: """Advance the cursor blocking for at most one getMore command.""" if not len(self._data) and not self._killed and get_more_allowed: self._refresh() @@ -170,7 +170,7 @@ def _try_next(self, get_more_allowed: bool) -> Optional[_DocumentType]: else: return None - def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] """Get all or some available documents from the cursor.""" if not len(self._data) and not self._killed: self._refresh() @@ -179,13 +179,14 @@ def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # typ result.extend(self._data) self._data.clear() else: + # A list comprehension here is slower or uses more memory. for _ in range(min(len(self._data), total)): - result.append(self._data.popleft()) + result.append(self._data.popleft()) # noqa: PERF401 return True else: return False - def try_next(self) -> Optional[_DocumentType]: + def try_next(self) -> _DocumentType | None: """Advance the cursor without blocking indefinitely. This method returns the next document without waiting @@ -211,10 +212,10 @@ def __init__( self, collection: Collection[_DocumentType], cursor_info: Mapping[str, Any], - address: Optional[_Address], + address: _Address | None, batch_size: int = 0, - max_await_time_ms: Optional[int] = None, - session: Optional[ClientSession] = None, + max_await_time_ms: int | None = None, + session: ClientSession | None = None, comment: Any = None, ) -> None: """Create a new cursor / iterator over raw batches of BSON data. @@ -239,9 +240,9 @@ def __init__( def _unpack_response( # type: ignore[override] self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions[dict[str, Any]], - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> list[Mapping[str, Any]]: raw_response = response.raw_response(cursor_id, user_fields=user_fields) diff --git a/pymongo/synchronous/command_runner.py b/pymongo/synchronous/command_runner.py index 9f37ce0308..3381f117a2 100644 --- a/pymongo/synchronous/command_runner.py +++ b/pymongo/synchronous/command_runner.py @@ -37,12 +37,9 @@ import datetime import time -from collections.abc import Callable, Mapping, MutableMapping, Sequence from typing import ( TYPE_CHECKING, Any, - Optional, - Union, cast, ) @@ -56,6 +53,8 @@ from pymongo.monitoring import _is_speculative_authenticate if TYPE_CHECKING: + from collections.abc import Callable, Mapping, MutableMapping, Sequence + from bson import CodecOptions from bson.objectid import ObjectId from pymongo.compression_support import SnappyContext, ZlibContext, ZstdContext @@ -79,19 +78,19 @@ def _run_command( request_id: int, msg: bytes, *, - client: Optional[MongoClient[Any]], - session: Optional[ClientSession], - listeners: Optional[_EventListeners], - topology_id: Optional[ObjectId], + client: MongoClient[Any] | None, + session: ClientSession | None, + listeners: _EventListeners | None, + topology_id: ObjectId | None, codec_options: CodecOptions[_DocumentType], - user_fields: Optional[Mapping[str, Any]] = None, - orig: Optional[MutableMapping[str, Any]] = None, - op_id: Optional[int] = None, - command_name: Optional[str] = None, + user_fields: Mapping[str, Any] | None = None, + orig: MutableMapping[str, Any] | None = None, + op_id: int | None = None, + command_name: str | None = None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, parse_write_concern_error: bool = False, - pool_opts: Optional[PoolOptions] = None, + pool_opts: PoolOptions | None = None, unacknowledged: bool = False, speculative_hello: bool = False, ensure_db: bool = False, @@ -99,9 +98,9 @@ def _run_command( max_doc_size: int = 0, more_to_come: bool = False, set_conn_more_to_come: bool = False, - unpack_res: Optional[Callable[..., Any]] = None, - cursor_id: Optional[int] = None, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], float]: + unpack_res: Callable[..., Any] | None = None, + cursor_id: int | None = None, +) -> tuple[list[dict[str, Any]], _OpMsg | None, float]: """Send ``msg`` over ``conn`` and return ``(docs, reply, duration_s)``, where ``duration_s`` is the round-trip duration in seconds. @@ -164,7 +163,7 @@ def _run_command( # Fast path: skip telemetry construction when logging and APM are disabled # Inline enabled check here for performance - telemetry: Optional[_CommandTelemetry] = None + telemetry: _CommandTelemetry | None = None if (topology_id is not None and _is_debug_enabled(_COMMAND_LOGGER)) or ( listeners is not None and listeners.enabled_for_commands ): @@ -176,7 +175,7 @@ def _run_command( else: start = time.monotonic() - reply: Optional[_OpMsg] = None + reply: _OpMsg | None = None docs: list[dict[str, Any]] = [{"ok": 1}] try: if more_to_come: @@ -247,11 +246,11 @@ def run_bulk_write_command( request_id: int, msg: bytes, *, - client: Optional[MongoClient[Any]], - orig: Optional[MutableMapping[str, Any]] = None, + client: MongoClient[Any] | None, + orig: MutableMapping[str, Any] | None = None, max_doc_size: int = 0, unacknowledged: bool = False, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], float]: +) -> tuple[list[dict[str, Any]], _OpMsg | None, float]: """Send a bulk write batch and return ``(docs, reply, duration_s)``. :param bwc: Bulk write context supplying the connection, session, listeners, etc. @@ -292,18 +291,18 @@ def run_cursor_command( request_id: int, msg: bytes, *, - client: Optional[MongoClient[Any]], - session: Optional[ClientSession], - listeners: Optional[_EventListeners], + client: MongoClient[Any] | None, + session: ClientSession | None, + listeners: _EventListeners | None, codec_options: CodecOptions[_DocumentType], command_name: str, - user_fields: Optional[Mapping[str, Any]] = None, - pool_opts: Optional[PoolOptions] = None, + user_fields: Mapping[str, Any] | None = None, + pool_opts: PoolOptions | None = None, max_doc_size: int = 0, more_to_come: bool = False, - unpack_res: Optional[Callable[..., Any]] = None, - cursor_id: Optional[int] = None, -) -> tuple[list[dict[str, Any]], Optional[_OpMsg], datetime.timedelta]: + unpack_res: Callable[..., Any] | None = None, + cursor_id: int | None = None, +) -> tuple[list[dict[str, Any]], _OpMsg | None, datetime.timedelta]: """Run a cursor ``find``/``getMore`` operation over ``conn``. :param conn: The Connection to send on. @@ -353,22 +352,22 @@ def run_command( conn: Connection, dbname: str, spec: MutableMapping[str, Any], - read_preference: Optional[_ServerMode], + read_preference: _ServerMode | None, codec_options: CodecOptions[_DocumentType], - session: Optional[ClientSession], - client: Optional[MongoClient[Any]], + session: ClientSession | None, + client: MongoClient[Any] | None, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - listeners: Optional[_EventListeners] = None, - max_bson_size: Optional[int] = None, - read_concern: Optional[ReadConcern] = None, + allowable_errors: Sequence[str | int] | None = None, + listeners: _EventListeners | None = None, + max_bson_size: int | None = None, + read_concern: ReadConcern | None = None, parse_write_concern_error: bool = False, - collation: Optional[_CollationIn] = None, - compression_ctx: Union[SnappyContext, ZlibContext, ZstdContext, None] = None, + collation: _CollationIn | None = None, + compression_ctx: SnappyContext | ZlibContext | ZstdContext | None = None, unacknowledged: bool = False, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, exhaust_allowed: bool = False, - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, ) -> _DocumentType: """Encode and execute a command over ``conn``, or raise socket.error. diff --git a/pymongo/synchronous/cursor.py b/pymongo/synchronous/cursor.py index 6d6dccf3de..b492372932 100644 --- a/pymongo/synchronous/cursor.py +++ b/pymongo/synchronous/cursor.py @@ -17,13 +17,10 @@ from __future__ import annotations from collections import deque -from collections.abc import Mapping from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, cast, overload, ) @@ -49,6 +46,8 @@ from pymongo.typings import _DocumentOut, _DocumentType if TYPE_CHECKING: + from collections.abc import Mapping + from bson.codec_options import CodecOptions from pymongo.synchronous.collection import Collection @@ -87,7 +86,7 @@ def __getitem__(self, index: int) -> _DocumentType: ... @overload def __getitem__(self, index: slice) -> Cursor[_DocumentType]: ... - def __getitem__(self, index: Union[int, slice]) -> Union[_DocumentType, Cursor[_DocumentType]]: + def __getitem__(self, index: int | slice) -> _DocumentType | Cursor[_DocumentType]: """Get a single document or a slice of documents from this cursor. .. warning:: A :class:`~Cursor` is not a Python :class:`list`. Each @@ -219,7 +218,7 @@ def distinct(self, key: str) -> list[Any]: return self._collection.distinct(key, session=self._session, **options) - def _send_message(self, operation: Union[_Query, _GetMore]) -> None: + def _send_message(self, operation: _Query | _GetMore) -> None: """Send a query or getmore operation and handles the response. If operation is ``None`` this is an exhaust cursor, which reads @@ -385,7 +384,7 @@ def next(self) -> _DocumentType: else: raise StopIteration - def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] """Get all or some documents from the cursor.""" if self._empty: return False @@ -394,8 +393,9 @@ def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # typ result.extend(self._data) self._data.clear() else: + # A list comprehension here is slower or uses more memory. for _ in range(min(len(self._data), total)): - result.append(self._data.popleft()) + result.append(self._data.popleft()) # noqa: PERF401 return True else: return False @@ -430,9 +430,9 @@ def __init__(self, collection: Collection[_DocumentType], *args: Any, **kwargs: def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: CodecOptions[Mapping[str, Any]], - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> list[_DocumentOut]: raw_response = response.raw_response(cursor_id, user_fields=user_fields) @@ -440,7 +440,7 @@ def _unpack_response( # OP_MSG returns firstBatch/nextBatch documents as a BSON array # Re-assemble the array of documents into a document stream _convert_raw_document_lists_to_streams(raw_response[0]) - return cast(list["_DocumentOut"], raw_response) + return cast("list[_DocumentOut]", raw_response) def explain(self) -> _DocumentType: """Returns an explain plan record for this cursor. diff --git a/pymongo/synchronous/cursor_base.py b/pymongo/synchronous/cursor_base.py index 0106f12645..b123c57880 100644 --- a/pymongo/synchronous/cursor_base.py +++ b/pymongo/synchronous/cursor_base.py @@ -17,8 +17,7 @@ from __future__ import annotations from abc import abstractmethod -from collections.abc import Mapping, Sequence -from typing import TYPE_CHECKING, Any, Optional, Union, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot from pymongo.cursor_shared import _CURSOR_DOC_FIELDS, _AgnosticCursorBase, _split_message @@ -30,6 +29,9 @@ from pymongo.typings import _DocumentOut, _DocumentType if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from types import TracebackType + from pymongo.read_preferences import _ServerMode from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.pool import Connection @@ -38,7 +40,7 @@ def _operation_to_command( - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, conn: Connection, apply_timeout: bool, ) -> tuple[dict[str, Any], str]: @@ -55,7 +57,7 @@ class _ConnectionManager: """Used with exhaust cursors to ensure the connection is returned.""" def __init__(self, conn: Connection, more_to_come: bool): - self.conn: Optional[Connection] = conn + self.conn: Connection | None = conn self.more_to_come = more_to_come self._lock = _create_lock() @@ -73,24 +75,24 @@ class _CursorBase(_AgnosticCursorBase[_DocumentType]): """Synchronous cursor base class.""" @property - def session(self) -> Optional[ClientSession]: + def session(self) -> ClientSession | None: """The cursor's :class:`~pymongo.client_session.ClientSession`, or None. .. versionadded:: 3.6 """ - return cast("Optional[ClientSession]", super().session) + return cast("ClientSession | None", super().session) @abstractmethod - def _next_batch(self, result: list, total: Optional[int] = None) -> bool: # type: ignore[type-arg] + def _next_batch(self, result: list, total: int | None = None) -> bool: # type: ignore[type-arg] ... @abstractmethod def _unpack_response( self, response: _OpMsg, - cursor_id: Optional[int], + cursor_id: int | None, codec_options: Any, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, legacy_response: bool = False, ) -> Sequence[_DocumentOut]: ... @@ -98,7 +100,7 @@ def _unpack_response( def _run_with_conn( self, conn: Connection, - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, read_preference: _ServerMode, ) -> Response: """Execute a cursor operation on the given connection and return a Response. @@ -187,11 +189,16 @@ def close(self) -> None: """Explicitly close / kill this cursor.""" self._die_lock() - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: self.close() @_csot.apply - def to_list(self, length: Optional[int] = None) -> list[_DocumentType]: + def to_list(self, length: int | None = None) -> list[_DocumentType]: """Converts the contents of this cursor to a list more efficiently than ``[doc for doc in cursor]``. To use:: diff --git a/pymongo/synchronous/database.py b/pymongo/synchronous/database.py index 65c5d2a7f0..746665f9b1 100644 --- a/pymongo/synchronous/database.py +++ b/pymongo/synchronous/database.py @@ -16,22 +16,18 @@ from __future__ import annotations -from collections.abc import Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Generic, NoReturn, - Optional, - Union, cast, overload, ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions from bson.dbref import DBRef -from bson.timestamp import Timestamp from pymongo import _csot, common from pymongo.common import _ecoc_coll_name, _esc_coll_name from pymongo.database_shared import _check_name, _CodecDocumentType @@ -45,8 +41,11 @@ from pymongo.typings import _CollationIn, _DocumentType, _DocumentTypeArg, _Pipeline if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping, Sequence + import bson import bson.codec_options + from bson.timestamp import Timestamp from pymongo.read_concern import ReadConcern from pymongo.synchronous.client_session import ClientSession from pymongo.synchronous.mongo_client import MongoClient @@ -62,10 +61,10 @@ def __init__( self, client: MongoClient[_DocumentType], name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> None: """Get a database by client and name. @@ -149,26 +148,26 @@ def name(self) -> str: def with_options( self, codec_options: None = None, - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> Database[_DocumentType]: ... @overload def with_options( self, codec_options: bson.CodecOptions[_DocumentTypeArg], - read_preference: Optional[_ServerMode] = ..., - write_concern: Optional[WriteConcern] = ..., - read_concern: Optional[ReadConcern] = ..., + read_preference: _ServerMode | None = ..., + write_concern: WriteConcern | None = ..., + read_concern: ReadConcern | None = ..., ) -> Database[_DocumentTypeArg]: ... def with_options( self, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> Database[_DocumentType] | Database[_DocumentTypeArg]: """Get a clone of this database changing the specified settings. @@ -209,12 +208,12 @@ def with_options( read_concern or self.read_concern, ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, Database): return self._client == other.client and self._name == other.name return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -249,10 +248,10 @@ def __getitem__(self, name: str) -> Collection[_DocumentType]: def get_collection( self, name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> Collection[_DocumentType]: """Get a :class:`~pymongo.collection.Collection` with the given name and options. @@ -302,10 +301,10 @@ def get_collection( def _get_encrypted_fields( self, kwargs: Mapping[str, Any], coll_name: str, ask_db: bool - ) -> Optional[Mapping[str, Any]]: + ) -> Mapping[str, Any] | None: encrypted_fields = kwargs.get("encryptedFields") if encrypted_fields: - return cast(Mapping[str, Any], deepcopy(encrypted_fields)) + return cast("Mapping[str, Any]", deepcopy(encrypted_fields)) if ( self.client.options.auto_encryption_opts and self.client.options.auto_encryption_opts._encrypted_fields_map @@ -314,7 +313,7 @@ def _get_encrypted_fields( ) ): return cast( - Mapping[str, Any], + "Mapping[str, Any]", deepcopy( self.client.options.auto_encryption_opts._encrypted_fields_map[ f"{self.name}.{coll_name}" @@ -324,7 +323,7 @@ def _get_encrypted_fields( if ask_db and self.client.options.auto_encryption_opts: options = self[coll_name].options() if options.get("encryptedFields"): - return cast(Mapping[str, Any], deepcopy(options["encryptedFields"])) + return cast("Mapping[str, Any]", deepcopy(options["encryptedFields"])) return None # See PYTHON-3084. @@ -344,18 +343,18 @@ def __bool__(self) -> NoReturn: def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[ClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: ClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> DatabaseChangeStream[_DocumentType]: """Watch changes on this database. @@ -477,12 +476,12 @@ def watch( def create_collection( self, name: str, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, - session: Optional[ClientSession] = None, - check_exists: Optional[bool] = True, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, + session: ClientSession | None = None, + check_exists: bool | None = True, **kwargs: Any, ) -> Collection[_DocumentType]: """Create a new :class:`~pymongo.collection.Collection` in this @@ -634,7 +633,7 @@ def create_collection( return coll def aggregate( - self, pipeline: _Pipeline, session: Optional[ClientSession] = None, **kwargs: Any + self, pipeline: _Pipeline, session: ClientSession | None = None, **kwargs: Any ) -> CommandCursor[_DocumentType]: """Perform a database-level aggregation. @@ -720,15 +719,15 @@ def aggregate( def _command( self, conn: Connection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[dict[str, Any]] = DEFAULT_CODEC_OPTIONS, - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, **kwargs: Any, ) -> dict[str, Any]: ... @@ -736,34 +735,33 @@ def _command( def _command( self, conn: Connection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[_CodecDocumentType] = ..., - write_concern: Optional[WriteConcern] = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, **kwargs: Any, ) -> _CodecDocumentType: ... def _command( self, conn: Connection, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: int = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, + allowable_errors: Sequence[str | int] | None = None, read_preference: _ServerMode = ReadPreference.PRIMARY, - codec_options: Union[ - CodecOptions[dict[str, Any]], CodecOptions[_CodecDocumentType] - ] = DEFAULT_CODEC_OPTIONS, - write_concern: Optional[WriteConcern] = None, + codec_options: CodecOptions[dict[str, Any]] + | CodecOptions[_CodecDocumentType] = DEFAULT_CODEC_OPTIONS, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, **kwargs: Any, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: """Internal command helper.""" if isinstance(command, str): command = {command: value} @@ -786,44 +784,44 @@ def _command( @overload def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, codec_options: None = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> dict[str, Any]: ... @overload def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, codec_options: CodecOptions[_CodecDocumentType] = ..., - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> _CodecDocumentType: ... @_csot.apply def command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[bson.codec_options.CodecOptions[_CodecDocumentType]] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + allowable_errors: Sequence[str | int] | None = None, + read_preference: _ServerMode | None = None, + codec_options: bson.codec_options.CodecOptions[_CodecDocumentType] | None = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: """Issue a MongoDB command. Send command `command` to the database and return the @@ -926,11 +924,11 @@ def command( read_preference = (session and session._txn_read_preference()) or ReadPreference.PRIMARY def inner( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, - ) -> Union[dict[str, Any], _CodecDocumentType]: + ) -> dict[str, Any] | _CodecDocumentType: return self._command( conn, command, @@ -950,13 +948,13 @@ def inner( @_csot.apply def cursor_command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], value: Any = 1, - read_preference: Optional[_ServerMode] = None, - codec_options: Optional[CodecOptions[_CodecDocumentType]] = None, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, - max_await_time_ms: Optional[int] = None, + read_preference: _ServerMode | None = None, + codec_options: CodecOptions[_CodecDocumentType] | None = None, + session: ClientSession | None = None, + comment: Any | None = None, + max_await_time_ms: int | None = None, **kwargs: Any, ) -> CommandCursor[_DocumentType]: """Issue a MongoDB command and parse the response as a cursor. @@ -1020,7 +1018,7 @@ def cursor_command( ) or ReadPreference.PRIMARY def inner( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, @@ -1057,15 +1055,15 @@ def inner( def _retryable_read_command( self, - command: Union[str, MutableMapping[str, Any]], + command: str | MutableMapping[str, Any], operation: str, - session: Optional[ClientSession] = None, + session: ClientSession | None = None, ) -> dict[str, Any]: """Same as command but used for retryable read commands.""" read_preference = (session and session._txn_read_preference()) or ReadPreference.PRIMARY def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, @@ -1082,13 +1080,13 @@ def _cmd( def _list_collections( self, conn: Connection, - session: Optional[ClientSession], + session: ClientSession | None, read_preference: _ServerMode, **kwargs: Any, ) -> CommandCursor[MutableMapping[str, Any]]: """Internal listCollections helper.""" coll = cast( - Collection[MutableMapping[str, Any]], + "Collection[MutableMapping[str, Any]]", self.get_collection("$cmd", read_preference=read_preference), ) cmd = {"listCollections": 1, "cursor": {}} @@ -1109,9 +1107,9 @@ def _list_collections( def _list_collections_helper( self, - session: Optional[ClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[MutableMapping[str, Any]]: """Get a cursor over the collections of this database. @@ -1140,7 +1138,7 @@ def _list_collections_helper( kwargs["comment"] = comment def _cmd( - session: Optional[ClientSession], + session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, @@ -1153,9 +1151,9 @@ def _cmd( def list_collections( self, - session: Optional[ClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[MutableMapping[str, Any]]: """Get a cursor over the collections of this database. @@ -1190,9 +1188,9 @@ def list_collections( def _list_collection_names( self, - session: Optional[ClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: if comment is not None: @@ -1214,16 +1212,16 @@ def _list_collection_names( def list_collection_names( self, - session: Optional[ClientSession] = None, - filter: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + filter: Mapping[str, Any] | None = None, + comment: Any | None = None, **kwargs: Any, ) -> list[str]: - """Get a list of all the collection names in this database. + r"""Get a list of all the collection names in this database. For example, to list all non-system collections:: - filter = {"name": {"$regex": r"^(?!system\\.)"}} + filter = {"name": {"$regex": r"^(?!system\.)"}} db.list_collection_names(filter=filter) :param session: a @@ -1247,14 +1245,14 @@ def list_collection_names( return self._list_collection_names(session, filter, comment, **kwargs) def _drop_helper( - self, name: str, session: Optional[ClientSession] = None, comment: Optional[Any] = None + self, name: str, session: ClientSession | None = None, comment: Any | None = None ) -> dict[str, Any]: command = {"drop": name} if comment is not None: command["comment"] = comment def inner( - session: Optional[ClientSession], conn: Connection, _retryable_write: bool + session: ClientSession | None, conn: Connection, _retryable_write: bool ) -> dict[str, Any]: return self._command( conn, @@ -1270,10 +1268,10 @@ def inner( @_csot.apply def drop_collection( self, - name_or_collection: Union[str, Collection[_DocumentTypeArg]], - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, - encrypted_fields: Optional[Mapping[str, Any]] = None, + name_or_collection: str | Collection[_DocumentTypeArg], + session: ClientSession | None = None, + comment: Any | None = None, + encrypted_fields: Mapping[str, Any] | None = None, ) -> dict[str, Any]: """Drop a collection. @@ -1347,12 +1345,12 @@ def drop_collection( def validate_collection( self, - name_or_collection: Union[str, Collection[_DocumentTypeArg]], + name_or_collection: str | Collection[_DocumentTypeArg], scandata: bool = False, full: bool = False, - session: Optional[ClientSession] = None, - background: Optional[bool] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + background: bool | None = None, + comment: Any | None = None, ) -> dict[str, Any]: """Validate a collection. @@ -1412,7 +1410,7 @@ def validate_collection( raise CollectionInvalid(f"{name} invalid: {info}") # Sharded results elif "raw" in result: - for _, res in result["raw"].items(): + for res in result["raw"].values(): if "result" in res: info = res["result"] if info.find("exception") != -1 or info.find("corrupt") != -1: @@ -1432,10 +1430,10 @@ def validate_collection( def dereference( self, dbref: DBRef, - session: Optional[ClientSession] = None, - comment: Optional[Any] = None, + session: ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, - ) -> Optional[_DocumentType]: + ) -> _DocumentType | None: """Dereference a :class:`~bson.dbref.DBRef`, getting the document it points to. diff --git a/pymongo/synchronous/encryption.py b/pymongo/synchronous/encryption.py index 1626c16f58..774e3347c2 100644 --- a/pymongo/synchronous/encryption.py +++ b/pymongo/synchronous/encryption.py @@ -16,19 +16,14 @@ from __future__ import annotations -import functools -import socket import time as time # noqa: PLC0414 # needed in sync version import uuid import weakref -from collections.abc import Generator, Mapping, MutableMapping, Sequence from copy import deepcopy from typing import ( TYPE_CHECKING, Any, Generic, - Optional, - Union, cast, ) @@ -52,15 +47,11 @@ from bson.codec_options import CodecOptions from bson.raw_bson import DEFAULT_RAW_BSON_OPTIONS, RawBSONDocument, _inflate_bson from pymongo import _csot, _op_id -from pymongo._kms_connect_shared import KMSConnectCallback from pymongo.daemon import _spawn_daemon from pymongo.encryption_options import ( AutoEncryptionOpts, RangeOpts, StringOpts, - # Re-exported for backwards compatibility: TextOpts is deprecated but must - # remain importable from this module until it is removed. - TextOpts, # noqa: F401 check_min_pymongocrypt, ) from pymongo.encryption_shared import ( @@ -87,11 +78,8 @@ _raise_connection_failure, ) from pymongo.read_concern import ReadConcern -from pymongo.results import DeleteResult from pymongo.ssl_support import BLOCKING_IO_ERRORS, get_ssl_context from pymongo.synchronous._kms_connect import _KMS_CONNECT_TIMEOUT, _connect_kms -from pymongo.synchronous.collection import Collection -from pymongo.synchronous.cursor import Cursor from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient from pymongo.typings import _DocumentType, _DocumentTypeArg @@ -99,8 +87,16 @@ from pymongo.write_concern import WriteConcern if TYPE_CHECKING: + from collections.abc import Generator, Mapping, MutableMapping, Sequence + from types import TracebackType + from pymongocrypt.mongocrypt import MongoCryptKmsContext + from pymongo._kms_connect_shared import KMSConnectCallback + from pymongo.results import DeleteResult + from pymongo.synchronous.collection import Collection + from pymongo.synchronous.cursor import Cursor + _IS_SYNC = True @@ -118,9 +114,9 @@ class _EncryptionIO(MongoCryptCallback): # type: ignore[misc] def __init__( self, - client: Optional[MongoClient[_DocumentTypeArg]], + client: MongoClient[_DocumentTypeArg] | None, key_vault_coll: Collection[_DocumentTypeArg], - mongocryptd_client: Optional[MongoClient[_DocumentTypeArg]], + mongocryptd_client: MongoClient[_DocumentTypeArg] | None, opts: AutoEncryptionOpts, ): """Internal class to perform I/O on behalf of pymongocrypt.""" @@ -130,8 +126,8 @@ def __init__( self.client_ref = weakref.ref(client) else: self.client_ref = None - self.key_vault_coll: Optional[Collection[RawBSONDocument]] = cast( - Collection[RawBSONDocument], + self.key_vault_coll: Collection[RawBSONDocument] | None = cast( + "Collection[RawBSONDocument]", key_vault_coll.with_options( codec_options=_KEY_VAULT_OPTS, read_concern=ReadConcern(level="majority"), @@ -211,7 +207,7 @@ def kms_request(self, kms_context: MongoCryptKmsContext) -> None: except Exception as exc: # Wrap I/O errors in PyMongo exceptions. if isinstance(exc, BLOCKING_IO_ERRORS): - exc = socket.timeout("timed out") + exc = TimeoutError("timed out") # Async raises an OSError instead of returning empty bytes. if isinstance(exc, OSError): msg_prefix = "KMS connection closed" @@ -239,7 +235,7 @@ def kms_request(self, kms_context: MongoCryptKmsContext) -> None: ) raise exc from final_err - def collection_info(self, database: str, filter: bytes) -> Optional[list[bytes]]: + def collection_info(self, database: str, filter: bytes) -> list[bytes] | None: """Get the collection info for a namespace. The returned collection info is passed to libmongocrypt which reads @@ -442,7 +438,7 @@ def encrypt( # TODO: PYTHON-1922 avoid decoding the encrypted_cmd. return _inflate_bson(encrypted_cmd, DEFAULT_RAW_BSON_OPTIONS) - def decrypt(self, response: bytes | memoryview) -> Optional[bytes]: + def decrypt(self, response: bytes | memoryview) -> bytes | None: """Decrypt a MongoDB command response. :param response: A MongoDB command response as BSON. @@ -453,7 +449,7 @@ def decrypt(self, response: bytes | memoryview) -> Optional[bytes]: with _wrap_encryption_errors(): # Don't let decryption's sub-commands inherit the in-flight op's id. with _op_id._OpIdContext(None): - return cast(bytes, self._auto_encrypter.decrypt(response)) + return cast("bytes", self._auto_encrypter.decrypt(response)) def _check_closed(self) -> None: if self._closed: @@ -468,47 +464,6 @@ def close(self) -> None: self._internal_client = None -@functools.lru_cache(maxsize=1) -def _string_opts_kwarg() -> str: - """The name the installed pymongocrypt gives the string index options. - - pymongocrypt renamed ``text_opts`` to ``string_opts`` in 1.19 and accepts - only one name per release. The rename landed on master before any release - carried it, so resolve the name from the installed signature rather than - from a version comparison. Resolved lazily and cached because importing - :mod:`inspect` is too expensive to do on the import path. - """ - import inspect - - params = inspect.signature(ExplicitEncrypter.encrypt).parameters - return "string_opts" if "string_opts" in params else "text_opts" - - -def _resolve_string_opts( - string_opts: Optional[StringOpts], text_opts: Optional[StringOpts] -) -> Optional[StringOpts]: - """Resolve string_opts and its former name, text_opts. - - pymongocrypt accepts only one of the two names per release, so passing the - name the installed pymongocrypt does not support is an error. - """ - if string_opts is not None and text_opts is not None: - raise ConfigurationError("Cannot set both string_opts and text_opts") - if string_opts is None and text_opts is None: - return None - if text_opts is not None and _string_opts_kwarg() == "string_opts": - raise ConfigurationError( - "text_opts is not supported by the installed pymongocrypt " - "(1.19 or later). Use string_opts instead." - ) - if string_opts is not None and _string_opts_kwarg() == "text_opts": - raise ConfigurationError( - "string_opts requires pymongocrypt 1.19 or later. Use text_opts " - "with the installed pymongocrypt, or upgrade pymongocrypt." - ) - return string_opts if string_opts is not None else text_opts - - class ClientEncryption(Generic[_DocumentType]): """Explicit client-side field level encryption.""" @@ -518,9 +473,9 @@ def __init__( key_vault_namespace: str, key_vault_client: MongoClient[_DocumentTypeArg], codec_options: CodecOptions[_DocumentTypeArg], - kms_tls_options: Optional[Mapping[str, Any]] = None, - key_expiration_ms: Optional[int] = None, - kms_connect_callback: Optional[KMSConnectCallback] = None, + kms_tls_options: Mapping[str, Any] | None = None, + key_expiration_ms: int | None = None, + kms_connect_callback: KMSConnectCallback | None = None, ) -> None: """Explicit client-side field level encryption. @@ -648,9 +603,7 @@ def __init__( kms_connect_callback=kms_connect_callback, ) self._kms_ssl_contexts = _parse_kms_tls_options(opts._kms_tls_options, _IS_SYNC) - self._io_callbacks: Optional[_EncryptionIO] = _EncryptionIO( - None, key_vault_coll, None, opts - ) + self._io_callbacks: _EncryptionIO | None = _EncryptionIO(None, key_vault_coll, None, opts) self._encryption = ExplicitEncrypter( self._io_callbacks, _create_mongocrypt_options( @@ -669,8 +622,8 @@ def create_encrypted_collection( database: Database[_DocumentTypeArg], name: str, encrypted_fields: Mapping[str, Any], - kms_provider: Optional[str] = None, - master_key: Optional[Mapping[str, Any]] = None, + kms_provider: str | None = None, + master_key: Mapping[str, Any] | None = None, **kwargs: Any, ) -> tuple[Collection[_DocumentTypeArg], Mapping[str, Any]]: """Create a collection with encryptedFields. @@ -756,9 +709,9 @@ def create_encrypted_collection( def create_data_key( self, kms_provider: str, - master_key: Optional[Mapping[str, Any]] = None, - key_alt_names: Optional[Sequence[str]] = None, - key_material: Optional[bytes] = None, + master_key: Mapping[str, Any] | None = None, + key_alt_names: Sequence[str] | None = None, + key_material: bytes | None = None, ) -> Binary: """Create and insert a new data key into the key vault collection. @@ -835,7 +788,7 @@ def create_data_key( self._check_closed() with _wrap_encryption_errors(): return cast( - Binary, + "Binary", self._encryption.create_data_key( kms_provider, master_key=master_key, @@ -848,13 +801,13 @@ def _encrypt_helper( self, value: Any, algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, is_expression: bool = False, - string_opts: Optional[StringOpts] = None, + string_opts: StringOpts | None = None, ) -> Any: self._check_closed() if isinstance(key_id, uuid.UUID): @@ -890,7 +843,7 @@ def _encrypt_helper( contention_factor=contention_factor, range_opts=range_opts_bytes, is_expression=is_expression, - **({_string_opts_kwarg(): string_opts_bytes} if string_opts_bytes else {}), + string_opts=string_opts_bytes, ) return decode(encrypted_doc)["v"] @@ -898,13 +851,12 @@ def encrypt( self, value: Any, algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, - string_opts: Optional[StringOpts] = None, - text_opts: Optional[StringOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, + string_opts: StringOpts | None = None, ) -> Binary: """Encrypt a BSON value with a given key and algorithm. @@ -927,13 +879,12 @@ def encrypt( :class:`RangeOpts` for some valid options. :param string_opts: Index options for `prefix`, `suffix`, and `substring` queries. See :class:`StringOpts` for some valid options. - :param text_opts: **DEPRECATED** - The former name of `string_opts`, - added in pymongocrypt 1.16 and accepted only through pymongocrypt - 1.18. Passing it to pymongocrypt 1.19 or later, or passing both - names, raises :exc:`~pymongo.errors.ConfigurationError`. :return: The encrypted value, a :class:`~bson.binary.Binary` with subtype 6. + .. versionchanged:: 4.20 + Removed the `text_opts` parameter. + .. versionchanged:: 4.18 Added the `string_opts` parameter, replacing the deprecated `text_opts`. @@ -951,7 +902,7 @@ def encrypt( Added the `query_type` and `contention_factor` parameters. """ return cast( - Binary, + "Binary", self._encrypt_helper( value=value, algorithm=algorithm, @@ -961,7 +912,7 @@ def encrypt( contention_factor=contention_factor, range_opts=range_opts, is_expression=False, - string_opts=_resolve_string_opts(string_opts, text_opts), + string_opts=string_opts, ), ) @@ -969,11 +920,11 @@ def encrypt_expression( self, expression: Mapping[str, Any], algorithm: str, - key_id: Optional[Union[Binary, uuid.UUID]] = None, - key_alt_name: Optional[str] = None, - query_type: Optional[str] = None, - contention_factor: Optional[int] = None, - range_opts: Optional[RangeOpts] = None, + key_id: Binary | uuid.UUID | None = None, + key_alt_name: str | None = None, + query_type: str | None = None, + contention_factor: int | None = None, + range_opts: RangeOpts | None = None, ) -> RawBSONDocument: """Encrypt a BSON expression with a given key and algorithm. @@ -1007,7 +958,7 @@ def encrypt_expression( .. versionadded:: 4.4 """ return cast( - RawBSONDocument, + "RawBSONDocument", self._encrypt_helper( value=expression, algorithm=algorithm, @@ -1037,7 +988,7 @@ def decrypt(self, value: Binary) -> Any: decrypted_doc = self._encryption.decrypt(doc) return decode(decrypted_doc, codec_options=self._codec_options)["v"] - def get_key(self, id: Binary) -> Optional[RawBSONDocument]: + def get_key(self, id: Binary) -> RawBSONDocument | None: """Get a data key by id. :param id` (Binary): The UUID of a key a which must be a @@ -1096,7 +1047,7 @@ def add_key_alt_name(self, id: Binary, key_alt_name: str) -> Any: assert self._key_vault_coll is not None return self._key_vault_coll.find_one_and_update({"_id": id}, update) - def get_key_by_alt_name(self, key_alt_name: str) -> Optional[RawBSONDocument]: + def get_key_by_alt_name(self, key_alt_name: str) -> RawBSONDocument | None: """Get a key document in the key vault collection that has the given ``key_alt_name``. :param key_alt_name: (str): The key alternate name of the key to get. @@ -1109,7 +1060,7 @@ def get_key_by_alt_name(self, key_alt_name: str) -> Optional[RawBSONDocument]: assert self._key_vault_coll is not None return self._key_vault_coll.find_one({"keyAltNames": key_alt_name}) - def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> Optional[RawBSONDocument]: + def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> RawBSONDocument | None: """Remove ``key_alt_name`` from the set of keyAltNames in the key document with UUID ``id``. Also removes the ``keyAltNames`` field from the key document if it would otherwise be empty. @@ -1148,8 +1099,8 @@ def remove_key_alt_name(self, id: Binary, key_alt_name: str) -> Optional[RawBSON def rewrap_many_data_key( self, filter: Mapping[str, Any], - provider: Optional[str] = None, - master_key: Optional[Mapping[str, Any]] = None, + provider: str | None = None, + master_key: Mapping[str, Any] | None = None, ) -> RewrapManyDataKeyResult: """Decrypts and encrypts all matching data keys in the key vault with a possibly new `master_key` value. @@ -1205,7 +1156,12 @@ def rewrap_many_data_key( def __enter__(self) -> ClientEncryption[_DocumentType]: return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: self.close() def _check_closed(self) -> None: diff --git a/pymongo/synchronous/helpers.py b/pymongo/synchronous/helpers.py index 695259c952..4038df19fa 100644 --- a/pymongo/synchronous/helpers.py +++ b/pymongo/synchronous/helpers.py @@ -72,7 +72,7 @@ def inner(*args: Any, **kwargs: Any) -> Any: return func(*args, **kwargs) raise - return cast(F, inner) + return cast("F", inner) def _getaddrinfo( diff --git a/pymongo/synchronous/mongo_client.py b/pymongo/synchronous/mongo_client.py index d9816b07a2..a4c29cb671 100644 --- a/pymongo/synchronous/mongo_client.py +++ b/pymongo/synchronous/mongo_client.py @@ -55,12 +55,10 @@ NoReturn, Optional, TypeVar, - Union, cast, ) from bson.codec_options import DEFAULT_CODEC_OPTIONS, CodecOptions, TypeRegistry -from bson.timestamp import Timestamp from pymongo import _csot, _op_id, common, helpers_shared, periodic_executor from pymongo.client_options import ClientOptions from pymongo.client_session_shared import SessionOptions, TransactionOptions, _EmptyServerSession @@ -100,7 +98,6 @@ _Op, ) from pymongo.read_preferences import ReadPreference, _ServerMode -from pymongo.results import ClientBulkWriteResult from pymongo.server_description import ServerDescription from pymongo.server_selectors import writable_server_selector from pymongo.server_type import SERVER_TYPE @@ -136,9 +133,11 @@ from types import TracebackType from bson.objectid import ObjectId + from bson.timestamp import Timestamp from pymongo.client_session_shared import _ServerSession from pymongo.read_concern import ReadConcern from pymongo.response import Response + from pymongo.results import ClientBulkWriteResult from pymongo.server_selectors import Selection from pymongo.synchronous.bulk import _Bulk from pymongo.synchronous.client_session import ClientSession @@ -158,14 +157,14 @@ _IS_SYNC = True -_WriteOp = Union[ - InsertOne, # type: ignore[type-arg] - DeleteOne, - DeleteMany, - ReplaceOne, # type: ignore[type-arg] - UpdateOne, - UpdateMany, -] +_WriteOp = ( + InsertOne # type: ignore[type-arg] + | DeleteOne + | DeleteMany + | ReplaceOne # type: ignore[type-arg] + | UpdateOne + | UpdateMany +) class MongoClient(common.BaseObject, Generic[_DocumentType]): @@ -178,12 +177,12 @@ class MongoClient(common.BaseObject, Generic[_DocumentType]): def __init__( self, - host: Optional[Union[str, Sequence[str]]] = None, - port: Optional[int] = None, - document_class: Optional[type[_DocumentType]] = None, - tz_aware: Optional[bool] = None, - connect: Optional[bool] = None, - type_registry: Optional[TypeRegistry] = None, + host: str | Sequence[str] | None = None, + port: int | None = None, + document_class: type[_DocumentType] | None = None, + tz_aware: bool | None = None, + connect: bool | None = None, + type_registry: TypeRegistry | None = None, **kwargs: Any, ) -> None: """Client for a MongoDB instance, a replica set, or a set of mongoses. @@ -927,7 +926,7 @@ def validator(host: str) -> bool: self._lock = _create_lock() self._kill_cursors_queue: list = [] # type: ignore[type-arg] - self._encrypter: Optional[_Encrypter] = None + self._encrypter: _Encrypter | None = None self._resolve_srv_info.update( { @@ -965,7 +964,7 @@ def validator(host: str) -> bool: self._opened = False self._closed = False - self._loop: Optional[asyncio.AbstractEventLoop] = None + self._loop: asyncio.AbstractEventLoop | None = None if not is_srv: self._init_background() @@ -1128,7 +1127,7 @@ def _connect(self) -> None: """Explicitly connect to MongoDB synchronously instead of on the first operation.""" self._get_topology() - def _init_background(self, old_pid: Optional[int] = None) -> None: + def _init_background(self, old_pid: int | None = None) -> None: self._topology = Topology(self._topology_settings) if _HAS_REGISTER_AT_FORK: # Add this client to the list of weakly referenced items. @@ -1165,14 +1164,13 @@ def append_metadata(self, driver_info: DriverInfo) -> None: .. versionadded:: 4.14 """ - if not isinstance(driver_info, DriverInfo): raise TypeError( f"driver_info must be an instance of DriverInfo, not {type(driver_info)}" ) self._options.pool_options._update_metadata(driver_info) - def _should_pin_cursor(self, session: Optional[ClientSession]) -> Optional[bool]: + def _should_pin_cursor(self, session: ClientSession | None) -> bool | None: return self._options.load_balanced and not (session and session.in_transaction) def _after_fork(self) -> None: @@ -1188,18 +1186,18 @@ def _duplicate(self, **kwargs: Any) -> MongoClient: # type: ignore[type-arg] def watch( self, - pipeline: Optional[_Pipeline] = None, - full_document: Optional[str] = None, - resume_after: Optional[Mapping[str, Any]] = None, - max_await_time_ms: Optional[int] = None, - batch_size: Optional[int] = None, - collation: Optional[_CollationIn] = None, - start_at_operation_time: Optional[Timestamp] = None, - session: Optional[client_session.ClientSession] = None, - start_after: Optional[Mapping[str, Any]] = None, - comment: Optional[Any] = None, - full_document_before_change: Optional[str] = None, - show_expanded_events: Optional[bool] = None, + pipeline: _Pipeline | None = None, + full_document: str | None = None, + resume_after: Mapping[str, Any] | None = None, + max_await_time_ms: int | None = None, + batch_size: int | None = None, + collation: _CollationIn | None = None, + start_at_operation_time: Timestamp | None = None, + session: client_session.ClientSession | None = None, + start_after: Mapping[str, Any] | None = None, + comment: Any | None = None, + full_document_before_change: str | None = None, + show_expanded_events: bool | None = None, ) -> ChangeStream[_DocumentType]: """Watch changes on this cluster. @@ -1349,7 +1347,7 @@ def topology_description(self) -> TopologyDescription: return self._topology.description @property - def _topology_id(self) -> Optional[ObjectId]: + def _topology_id(self) -> ObjectId | None: return self._topology_settings._topology_id @property @@ -1378,7 +1376,7 @@ def options(self) -> ClientOptions: """ return self._options - def eq_props(self) -> tuple[tuple[_Address, ...], Optional[str], Optional[str], str]: + def eq_props(self) -> tuple[tuple[_Address, ...], str | None, str | None, str]: return ( tuple(sorted(self._resolve_srv_info["seeds"])), self._options.replica_set_name, @@ -1386,12 +1384,12 @@ def eq_props(self) -> tuple[tuple[_Address, ...], Optional[str], Optional[str], self._resolve_srv_info["srv_service_name"], ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, self.__class__): return self.eq_props() == other.eq_props() return NotImplemented - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: return not self == other def __hash__(self) -> int: @@ -1483,8 +1481,8 @@ def __del__(self) -> None: def _close_cursor_soon( self, cursor_id: int, - address: Optional[_CursorAddress], - conn_mgr: Optional[_ConnectionManager] = None, + address: _CursorAddress | None, + conn_mgr: _ConnectionManager | None = None, ) -> None: """Request that a cursor and/or connection be cleaned up soon.""" self._kill_cursors_queue.append((address, cursor_id, conn_mgr)) @@ -1496,9 +1494,9 @@ def _start_session(self, implicit: bool, **kwargs: Any) -> ClientSession: def start_session( self, - causal_consistency: Optional[bool] = None, - default_transaction_options: Optional[TransactionOptions] = None, - snapshot: Optional[bool] = False, + causal_consistency: bool | None = None, + default_transaction_options: TransactionOptions | None = None, + snapshot: bool | None = False, ) -> client_session.ClientSession: """Start a logical session. @@ -1523,7 +1521,7 @@ def start_session( snapshot=snapshot, ) - def _ensure_session(self, session: Optional[ClientSession] = None) -> Optional[ClientSession]: + def _ensure_session(self, session: ClientSession | None = None) -> ClientSession | None: """If provided session and bound session are None, lend a temporary session.""" session = session or self._get_bound_session() if session: @@ -1538,13 +1536,13 @@ def _ensure_session(self, session: Optional[ClientSession] = None) -> Optional[C return None def _send_cluster_time( - self, command: MutableMapping[str, Any], session: Optional[ClientSession] + self, command: MutableMapping[str, Any], session: ClientSession | None ) -> None: topology_time = self._topology.max_cluster_time() session_time = session.cluster_time if session else None if topology_time and session_time: if topology_time["clusterTime"] > session_time["clusterTime"]: - cluster_time: Optional[ClusterTime] = topology_time + cluster_time: ClusterTime | None = topology_time else: cluster_time = session_time else: @@ -1554,11 +1552,11 @@ def _send_cluster_time( def get_default_database( self, - default: Optional[str] = None, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + default: str | None = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> database.Database[_DocumentType]: """Get the database named in the MongoDB connection URI. @@ -1607,18 +1605,18 @@ def get_default_database( if self._default_database_name is None and default is None: raise ConfigurationError("No default database name defined or provided.") - name = cast(str, self._default_database_name or default) + name = cast("str", self._default_database_name or default) return database.Database( self, name, codec_options, read_preference, write_concern, read_concern ) def get_database( self, - name: Optional[str] = None, - codec_options: Optional[CodecOptions[_DocumentTypeArg]] = None, - read_preference: Optional[_ServerMode] = None, - write_concern: Optional[WriteConcern] = None, - read_concern: Optional[ReadConcern] = None, + name: str | None = None, + codec_options: CodecOptions[_DocumentTypeArg] | None = None, + read_preference: _ServerMode | None = None, + write_concern: WriteConcern | None = None, + read_concern: ReadConcern | None = None, ) -> database.Database[_DocumentType]: """Get a :class:`~pymongo.database.Database` with the given name and options. @@ -1683,7 +1681,12 @@ def _database_default_options(self, name: str) -> database.Database: # type: ig def __enter__(self) -> MongoClient[_DocumentType]: return self - def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, + ) -> None: self.close() # See PYTHON-3084. @@ -1710,7 +1713,7 @@ def _server_property(self, attr_name: str) -> Any: return getattr(server.description, attr_name) @property - def address(self) -> Optional[tuple[str, int]]: + def address(self) -> tuple[str, int] | None: """(host, port) of the current standalone, primary, or mongos, or None. Accessing :attr:`address` raises :exc:`~.errors.InvalidOperation` if @@ -1737,7 +1740,7 @@ def address(self) -> Optional[tuple[str, int]]: return self._server_property("address") @property - def primary(self) -> Optional[tuple[str, int]]: + def primary(self) -> tuple[str, int] | None: """The (host, port) of the current primary of the replica set. Returns ``None`` if this client is not connected to a replica set, @@ -1882,17 +1885,17 @@ def _get_topology(self) -> Topology: self._opened = True return self._topology - def _checkout(self, server: Server, session: Optional[ClientSession]) -> _ClientCheckout: + def _checkout(self, server: Server, session: ClientSession | None) -> _ClientCheckout: return _ClientCheckout(self, server, session) def _select_server( self, server_selector: Callable[[Selection], Selection], - session: Optional[ClientSession], + session: ClientSession | None, operation: str, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: """Select a server to run an operation on this client. @@ -1934,12 +1937,12 @@ def _select_server( session._unpin() raise - def _conn_for_writes(self, session: Optional[ClientSession], operation: str) -> _ClientCheckout: + def _conn_for_writes(self, session: ClientSession | None, operation: str) -> _ClientCheckout: server = self._select_server(writable_server_selector, session, operation) return self._checkout(server, session) def _conn_from_server( - self, read_preference: _ServerMode, server: Server, session: Optional[ClientSession] + self, read_preference: _ServerMode, server: Server, session: ClientSession | None ) -> _ClientReadCheckout: assert read_preference is not None, "read_preference must not be None" return _ClientReadCheckout(self, server, session, read_preference) @@ -1947,7 +1950,7 @@ def _conn_from_server( def _conn_for_reads( self, read_preference: _ServerMode, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, ) -> _ClientReadCheckout: assert read_preference is not None, "read_preference must not be None" @@ -1957,9 +1960,9 @@ def _conn_for_reads( @_csot.apply def _run_operation( self, - operation: Union[_Query, _GetMore], + operation: _Query | _GetMore, run_with_conn: Callable, # type: ignore[type-arg] - address: Optional[_Address] = None, + address: _Address | None = None, ) -> Response: """Run a _Query/_GetMore operation and return a Response. @@ -1969,27 +1972,9 @@ def _run_operation( :param address: Optional address when sending a message to a specific server, used for getMore. """ - if operation.conn_mgr: - server = self._select_server( - operation.read_preference, - operation.session, # type: ignore[arg-type] - operation.name, - address=address, - ) - - with operation.conn_mgr._lock: - with _ClientCheckout.for_existing_conn( - self, - server, - operation.session, # type: ignore[arg-type] - operation.conn_mgr.conn, - ): - return run_with_conn( - operation.conn_mgr.conn, operation, operation.read_preference - ) def _cmd( - _session: Optional[ClientSession], + _session: ClientSession | None, _server: Server, conn: Connection, read_preference: _ServerMode, @@ -2004,16 +1989,17 @@ def _cmd( address=address, retryable=isinstance(operation, _Query), operation=operation.name, + conn_mgr=operation.conn_mgr, ) def _retry_with_session( self, retryable: bool, func: _WriteCall[T], - session: Optional[ClientSession], - bulk: Optional[Union[_Bulk, _ClientBulk]], + session: ClientSession | None, + bulk: _Bulk | _ClientBulk | None, operation: str, - operation_id: Optional[int] = None, + operation_id: int | None = None, ) -> T: """Execute an operation with at most one consecutive retries @@ -2040,16 +2026,17 @@ def _retry_with_session( def _retry_internal( self, func: _WriteCall[T] | _ReadCall[T], - session: Optional[ClientSession], - bulk: Optional[Union[_Bulk, _ClientBulk]], + session: ClientSession | None, + bulk: _Bulk | _ClientBulk | None, operation: str, is_read: bool = False, - address: Optional[_Address] = None, - read_pref: Optional[_ServerMode] = None, + address: _Address | None = None, + read_pref: _ServerMode | None = None, retryable: bool = False, - operation_id: Optional[int] = None, + operation_id: int | None = None, is_run_command: bool = False, is_aggregate_write: bool = False, + conn_mgr: Any = None, ) -> T: """Internal retryable helper for all client transactions. @@ -2064,6 +2051,7 @@ def _retry_internal( :param is_run_command: If this is a runCommand operation, defaults to False :param is_aggregate_write: If this is a aggregate operation with a write, defaults to False. :param operation_id: Stable operation id shared across retries, defaults to None + :param conn_mgr: Pinned connection manager, defaults to None :return: Output of the calling func() """ @@ -2080,19 +2068,21 @@ def _retry_internal( operation_id=operation_id, is_run_command=is_run_command, is_aggregate_write=is_aggregate_write, + conn_mgr=conn_mgr, ).run() def _retryable_read( self, func: _ReadCall[T], read_pref: _ServerMode, - session: Optional[ClientSession], + session: ClientSession | None, operation: str, - address: Optional[_Address] = None, + address: _Address | None = None, retryable: bool = True, - operation_id: Optional[int] = None, + operation_id: int | None = None, is_run_command: bool = False, is_aggregate_write: bool = False, + conn_mgr: Any = None, ) -> T: """Execute an operation with consecutive retries if possible @@ -2111,8 +2101,8 @@ def _retryable_read( :param is_run_command: If this is a runCommand operation, defaults to False. :param is_aggregate_write: If this is a aggregate operation with a write, defaults to False. :param operation_id: Stable operation id shared across retries, defaults to None + :param conn_mgr: Pinned connection manager, defaults to None """ - # Ensure that the client supports retrying on reads and there is no session in # transaction, otherwise, we will not support retry behavior for this call. retryable = bool( @@ -2131,16 +2121,17 @@ def _retryable_read( operation_id=operation_id, is_run_command=is_run_command, is_aggregate_write=is_aggregate_write, + conn_mgr=conn_mgr, ) def _retryable_write( self, retryable: bool, func: _WriteCall[T], - session: Optional[ClientSession], + session: ClientSession | None, operation: str, - bulk: Optional[Union[_Bulk, _ClientBulk]] = None, - operation_id: Optional[int] = None, + bulk: _Bulk | _ClientBulk | None = None, + operation_id: int | None = None, ) -> T: """Execute an operation with consecutive retries if possible @@ -2162,9 +2153,9 @@ def _retryable_write( def _cleanup_cursor_no_lock( self, cursor_id: int, - address: Optional[_CursorAddress], + address: _CursorAddress | None, conn_mgr: _ConnectionManager, - session: Optional[ClientSession], + session: ClientSession | None, ) -> None: """Cleanup a cursor from __del__ without locking. @@ -2185,9 +2176,9 @@ def _cleanup_cursor_no_lock( def _cleanup_cursor_lock( self, cursor_id: int, - address: Optional[_CursorAddress], + address: _CursorAddress | None, conn_mgr: _ConnectionManager, - session: Optional[ClientSession], + session: ClientSession | None, ) -> None: """Cleanup a cursor from cursor.close() using a lock. @@ -2217,9 +2208,9 @@ def _cleanup_cursor_lock( def _close_cursor_now( self, cursor_id: int, - address: Optional[_CursorAddress], - session: Optional[ClientSession] = None, - conn_mgr: Optional[_ConnectionManager] = None, + address: _CursorAddress | None, + session: ClientSession | None = None, + conn_mgr: _ConnectionManager | None = None, ) -> None: """Send a kill cursors message with the given id. @@ -2244,9 +2235,9 @@ def _close_cursor_now( def _kill_cursors( self, cursor_ids: Sequence[int], - address: Optional[_CursorAddress], + address: _CursorAddress | None, topology: Topology, - session: Optional[ClientSession], + session: ClientSession | None, ) -> None: """Send a kill cursors message with the given ids.""" if address: @@ -2265,7 +2256,7 @@ def _kill_cursor_impl( self, cursor_ids: Sequence[int], address: _CursorAddress, - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, ) -> None: namespace = address.namespace @@ -2327,9 +2318,7 @@ def _process_periodic_tasks(self) -> None: else: _log_client_error() - def _return_server_session( - self, server_session: Union[_ServerSession, _EmptyServerSession] - ) -> None: + def _return_server_session(self, server_session: _ServerSession | _EmptyServerSession) -> None: """Internal: return a _ServerSession to the pool.""" if isinstance(server_session, _EmptyServerSession): return None @@ -2337,8 +2326,8 @@ def _return_server_session( @contextlib.contextmanager def _tmp_session( - self, session: Optional[client_session.ClientSession] - ) -> Generator[Optional[client_session.ClientSession], None]: + self, session: client_session.ClientSession | None + ) -> Generator[client_session.ClientSession | None, None]: """If provided session is None, lend a temporary session.""" if session is not None and not isinstance(session, client_session.ClientSession): raise ValueError( @@ -2370,12 +2359,12 @@ def _tmp_session( else: yield None - def _process_response(self, reply: Mapping[str, Any], session: Optional[ClientSession]) -> None: + def _process_response(self, reply: Mapping[str, Any], session: ClientSession | None) -> None: self._topology.receive_cluster_time(reply.get("$clusterTime")) if session is not None: session._process_response(reply) - def _get_bound_session(self) -> Optional[ClientSession]: + def _get_bound_session(self) -> ClientSession | None: bound_session = _SESSION.get() if bound_session: if bound_session.client is self: @@ -2387,7 +2376,7 @@ def _get_bound_session(self) -> Optional[ClientSession]: else: return None - def server_info(self, session: Optional[client_session.ClientSession] = None) -> dict[str, Any]: + def server_info(self, session: client_session.ClientSession | None = None) -> dict[str, Any]: """Get information about the MongoDB server we're connected to. :param session: a @@ -2397,7 +2386,7 @@ def server_info(self, session: Optional[client_session.ClientSession] = None) -> Added ``session`` parameter. """ return cast( # type: ignore[redundant-cast] - dict[str, Any], + "dict[str, Any]", self.admin.command( "buildinfo", read_preference=ReadPreference.PRIMARY, session=session ), @@ -2405,8 +2394,8 @@ def server_info(self, session: Optional[client_session.ClientSession] = None) -> def _list_databases( self, - session: Optional[client_session.ClientSession] = None, - comment: Optional[Any] = None, + session: client_session.ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[dict[str, Any]]: cmd = {"listDatabases": 1} @@ -2425,8 +2414,8 @@ def _list_databases( def list_databases( self, - session: Optional[client_session.ClientSession] = None, - comment: Optional[Any] = None, + session: client_session.ClientSession | None = None, + comment: Any | None = None, **kwargs: Any, ) -> CommandCursor[dict[str, Any]]: """Get a cursor over the databases of the connected server. @@ -2459,8 +2448,8 @@ def list_databases( def list_database_names( self, - session: Optional[client_session.ClientSession] = None, - comment: Optional[Any] = None, + session: client_session.ClientSession | None = None, + comment: Any | None = None, ) -> list[str]: """Get a list of the names of all databases on the connected server. @@ -2480,9 +2469,9 @@ def list_database_names( @_csot.apply def drop_database( self, - name_or_database: Union[str, database.Database[_DocumentTypeArg]], - session: Optional[client_session.ClientSession] = None, - comment: Optional[Any] = None, + name_or_database: str | database.Database[_DocumentTypeArg], + session: client_session.ClientSession | None = None, + comment: Any | None = None, ) -> None: """Drop a database. @@ -2532,13 +2521,13 @@ def drop_database( def bulk_write( self, models: Sequence[_WriteOp], - session: Optional[ClientSession] = None, + session: ClientSession | None = None, ordered: bool = True, verbose_results: bool = False, - bypass_document_validation: Optional[bool] = None, - comment: Optional[Any] = None, - let: Optional[Mapping[str, Any]] = None, - write_concern: Optional[WriteConcern] = None, + bypass_document_validation: bool | None = None, + comment: Any | None = None, + let: Mapping[str, Any] | None = None, + write_concern: WriteConcern | None = None, ) -> ClientBulkWriteResult: """Send a batch of write operations, potentially across multiple namespaces, to the server. @@ -2686,7 +2675,7 @@ def __init__( self, client: MongoClient, # type: ignore[type-arg] server: Server, - session: Optional[ClientSession], + session: ClientSession | None, ): if not isinstance(client, MongoClient): # This is for compatibility with mocked and subclassed types, such as in Motor. @@ -2703,10 +2692,10 @@ def __init__( # of the pool at the time the connection attempt was started." self.sock_generation = server.pool.gen.get_overall() self.completed_handshake = False - self.service_id: Optional[ObjectId] = None + self.service_id: ObjectId | None = None self.handled = False - self._existing_conn: Optional[Connection] = None - self._pool_checkout: Optional[_PoolCheckout] = None + self._existing_conn: Connection | None = None + self._pool_checkout: _PoolCheckout | None = None self._server = server def contribute_socket(self, conn: Connection, completed_handshake: bool = True) -> None: @@ -2716,9 +2705,7 @@ def contribute_socket(self, conn: Connection, completed_handshake: bool = True) self.service_id = conn.service_id self.completed_handshake = completed_handshake - def handle( - self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException] - ) -> None: + def handle(self, exc_type: type[BaseException] | None, exc_val: BaseException | None) -> None: if self.handled or exc_val is None: return self.handled = True @@ -2794,9 +2781,9 @@ def __enter__(self) -> Connection: def __exit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: # Perform SDAM error handling while the connection is still checked out. try: @@ -2812,7 +2799,7 @@ def for_existing_conn( cls, client: MongoClient, # type: ignore[type-arg] server: Server, - session: Optional[ClientSession], + session: ClientSession | None, conn: Connection, ) -> _ClientCheckout: """Return a _ClientCheckout for an already-checked-out connection. @@ -2839,7 +2826,7 @@ def __init__( self, client: MongoClient, # type: ignore[type-arg] server: Server, - session: Optional[ClientSession], + session: ClientSession | None, read_preference: _ServerMode, ) -> None: super().__init__(client, server, session) @@ -2869,7 +2856,7 @@ class _ClientConnectionRetryable( __slots__ = () _client: MongoClient[Any] - _session: Optional[ClientSession] + _session: ClientSession | None def run(self) -> T: """Runs the supplied func() and attempts a retry @@ -2940,6 +2927,11 @@ def run(self) -> T: ) ): raise + if self._conn_mgr is not None and self._conn_mgr.more_to_come: + # A receive-only exhaust getMore has no request + # in flight to retry: the error reply ends the + # stream. + raise self._retrying = True self._last_error = exc_to_check self._attempt_number += 1 @@ -3078,19 +3070,30 @@ def _read(self) -> T: """ self._server = self._get_server() assert self._read_pref is not None, "Read Preference required on read calls" + if self._conn_mgr is not None: + # The cursor is pinned to a connection (e.g. load-balanced mode): + # retry on that same connection. + with self._conn_mgr._lock: + with _ClientCheckout.for_existing_conn( + self._client, self._server, self._session, self._conn_mgr.conn + ): + return self._run_read_func(self._conn_mgr.conn, self._read_pref) with self._client._conn_from_server(self._read_pref, self._server, self._session) as ( conn, read_pref, ): - if self._retrying and not self._retryable and not self._always_retryable: - self._check_last_error() - if self._retrying: - self._log_retry(is_write=False) - # One operation id across all attempts of this operation if APM/logging is enabled - if self._operation_id is None: - return self._func(self._session, self._server, conn, read_pref) # type: ignore - with _op_id._OpIdContext(self._operation_id): - return self._func(self._session, self._server, conn, read_pref) # type: ignore + return self._run_read_func(conn, read_pref) + + def _run_read_func(self, conn: Connection, read_pref: _ServerMode) -> T: + if self._retrying and not self._retryable and not self._always_retryable: + self._check_last_error() + if self._retrying: + self._log_retry(is_write=False) + # One operation id across all attempts of this operation if APM/logging is enabled + if self._operation_id is None: + return self._func(self._session, self._server, conn, read_pref) # type: ignore + with _op_id._OpIdContext(self._operation_id): + return self._func(self._session, self._server, conn, read_pref) # type: ignore if _HAS_REGISTER_AT_FORK: diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index 9708c6e1a2..436e9eed8b 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -21,12 +21,12 @@ import threading import time import weakref -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from pymongo import common, periodic_executor from pymongo._csot import MovingMinimum from pymongo._telemetry import _HeartbeatTelemetry, _monotonic_duration, log_srv_monitor_failure -from pymongo.errors import NetworkTimeout, _OperationCancelled +from pymongo.errors import ConfigurationError, NetworkTimeout, _OperationCancelled from pymongo.hello import Hello from pymongo.lock import _create_lock from pymongo.periodic_executor import _shutdown_executors @@ -77,7 +77,7 @@ def target() -> bool: self._executor = executor - def _on_topology_gc(dummy: Optional[Topology] = None) -> None: + def _on_topology_gc(dummy: Topology | None = None) -> None: # This prevents GC from waiting 10 seconds for hello to complete # See test_cleanup_executors_on_client_del. monitor = self_ref() @@ -142,9 +142,9 @@ def __init__( self._pool = pool self._settings = topology_settings self._listeners = self._settings._pool_options._event_listeners - self._cancel_context: Optional[_CancellationContext] = None - self._conn_id: Optional[int] = None - self._current_hb: Optional[_HeartbeatTelemetry] = None + self._cancel_context: _CancellationContext | None = None + self._conn_id: int | None = None + self._current_hb: _HeartbeatTelemetry | None = None self._awaited: bool = False self._rtt_monitor = _RttMonitor( topology, @@ -357,7 +357,7 @@ def _run(self) -> None: # Topology was garbage-collected. self.close() - def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]: + def _get_seedlist(self) -> list[tuple[str, Any]] | None: """Poll SRV records for a seedlist. Returns a list of ServerDescriptions. @@ -373,7 +373,7 @@ def _get_seedlist(self) -> Optional[list[tuple[str, Any]]]: seedlist, ttl = resolver.get_hosts_and_min_ttl() if len(seedlist) == 0: # As per the spec: this should be treated as a failure. - raise Exception + raise ConfigurationError("SRV polling returned no valid hosts.") except Exception as exc: # As per the spec, upon encountering an error: # - An error must not be raised @@ -417,7 +417,7 @@ def add_sample(self, sample: float) -> None: self._moving_average.add_sample(sample) self._moving_min.add_sample(sample) - def get(self) -> tuple[Optional[float], float]: + def get(self) -> tuple[float | None, float]: """Get the calculated average, or None if no samples yet and the min.""" with self._lock: return self._moving_average.get(), self._moving_min.get() @@ -449,7 +449,7 @@ def _ping(self) -> float: """Run a "hello" command and return the RTT.""" with self._pool.checkout() as conn: if self._executor._stopped: - raise Exception("_RttMonitor closed") + raise Exception("_RttMonitor closed") # noqa: TRY002 start = time.monotonic() conn.hello() return _monotonic_duration(start) diff --git a/pymongo/synchronous/pool.py b/pymongo/synchronous/pool.py index de5fbb0e85..45f8af4ec6 100644 --- a/pymongo/synchronous/pool.py +++ b/pymongo/synchronous/pool.py @@ -18,13 +18,10 @@ import collections import os import time -from collections.abc import Mapping, MutableMapping, Sequence from typing import ( TYPE_CHECKING, Any, NoReturn, - Optional, - Union, ) from bson import DEFAULT_CODEC_OPTIONS @@ -55,7 +52,9 @@ ConnectionClosedReason, ) from pymongo.network_layer import NetworkingInterface, receive_message, sendall -from pymongo.pool_options import PoolOptions + +# Needed for backwards-compatible imports from pool.py. +from pymongo.pool_options import PoolOptions # noqa: TC001 from pymongo.pool_shared import ( _UNDO_OPERATION_COUNT, _UNDO_PENDING, @@ -76,6 +75,7 @@ from pymongo.synchronous.helpers import _handle_reauth if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping, Sequence from types import TracebackType from bson import CodecOptions @@ -126,8 +126,8 @@ def hello(self) -> Hello[dict[str, Any]]: def _hello( self, - topology_version: Optional[Any], - heartbeat_frequency: Optional[int], + topology_version: Any | None, + heartbeat_frequency: int | None, ) -> Hello[dict[str, Any]]: cmd = self.hello_cmd() performing_handshake = not self.performed_handshake @@ -179,7 +179,7 @@ def _hello( self.supports_sessions = ( hello.logical_session_timeout_minutes is not None and hello.is_readable ) - self.logical_session_timeout_minutes: Optional[int] = hello.logical_session_timeout_minutes + self.logical_session_timeout_minutes: int | None = hello.logical_session_timeout_minutes # hello_ok is set from helloOk, which is only returned from ismaster # don't overwrite this when connection switches to hello self.hello_ok = self.hello_ok or hello.hello_ok @@ -229,16 +229,16 @@ def command( read_preference: _ServerMode = ReadPreference.PRIMARY, codec_options: CodecOptions[Mapping[str, Any]] = DEFAULT_CODEC_OPTIONS, # type: ignore[assignment] check: bool = True, - allowable_errors: Optional[Sequence[Union[str, int]]] = None, - read_concern: Optional[ReadConcern] = None, - write_concern: Optional[WriteConcern] = None, + allowable_errors: Sequence[str | int] | None = None, + read_concern: ReadConcern | None = None, + write_concern: WriteConcern | None = None, parse_write_concern_error: bool = False, - collation: Optional[_CollationIn] = None, - session: Optional[ClientSession] = None, - client: Optional[MongoClient[Any]] = None, + collation: _CollationIn | None = None, + session: ClientSession | None = None, + client: MongoClient[Any] | None = None, retryable_write: bool = False, publish_events: bool = True, - user_fields: Optional[Mapping[str, Any]] = None, + user_fields: Mapping[str, Any] | None = None, exhaust_allowed: bool = False, ) -> dict[str, Any]: """Execute a command or raise an error. @@ -327,7 +327,7 @@ def send_message(self, message: bytes, max_doc_size: int) -> None: except BaseException as error: self._raise_connection_failure(error) - def receive_message(self, request_id: Optional[int]) -> _OpMsg: + def receive_message(self, request_id: int | None) -> _OpMsg: """Receive a raw BSON message or raise ConnectionFailure. If any exception is raised, the socket is closed. @@ -359,7 +359,7 @@ def authenticate(self, reauthenticate: bool = False) -> None: self.ready = True self._telemetry.connection_ready(self.id, self.creation_time) - def close_conn(self, reason: Optional[str]) -> None: + def close_conn(self, reason: str | None) -> None: """Close this connection with a reason.""" if self.closed: return @@ -429,7 +429,7 @@ def __init__( address: _Address, options: PoolOptions, is_sdam: bool = False, - client_id: Optional[ObjectId] = None, + client_id: ObjectId | None = None, ): """ :param address: a (hostname, port) tuple @@ -459,7 +459,7 @@ def _reset( self, close: bool, pause: bool = True, - service_id: Optional[ObjectId] = None, + service_id: ObjectId | None = None, interrupt_connections: bool = False, ) -> None: old_state = self.state @@ -530,7 +530,7 @@ def _reset( for conn in sockets: conn.close_conn(ConnectionClosedReason.STALE) - def update_is_writable(self, is_writable: Optional[bool]) -> None: + def update_is_writable(self, is_writable: bool | None) -> None: """Updates the is_writable attribute on all sockets currently in the Pool. """ @@ -540,7 +540,7 @@ def update_is_writable(self, is_writable: Optional[bool]) -> None: _socket.update_is_writable(self.is_writable) # type: ignore[arg-type] def reset( - self, service_id: Optional[ObjectId] = None, interrupt_connections: bool = False + self, service_id: ObjectId | None = None, interrupt_connections: bool = False ) -> None: self._reset(close=False, service_id=service_id, interrupt_connections=interrupt_connections) @@ -619,7 +619,7 @@ def remove_stale_sockets(self, reference_generation: int) -> None: self.requests -= 1 self.size_cond.notify() - def connect(self, handler: Optional[_ClientCheckout] = None) -> Connection: + def connect(self, handler: _ClientCheckout | None = None) -> Connection: """Connect to Mongo and return a new Connection. Can raise ConnectionFailure. @@ -687,7 +687,7 @@ def connect(self, handler: Optional[_ClientCheckout] = None) -> Connection: return conn - def checkout(self, handler: Optional[_ClientCheckout] = None) -> _PoolCheckout: + def checkout(self, handler: _ClientCheckout | None = None) -> _PoolCheckout: """Get a connection from the pool. Always use in a with statement:: with pool.checkout() as connection: @@ -701,7 +701,7 @@ def checkout(self, handler: Optional[_ClientCheckout] = None) -> _PoolCheckout: return _PoolCheckout(self, handler) def _get_conn( - self, checkout_started_time: float, handler: Optional[_ClientCheckout] = None + self, checkout_started_time: float, handler: _ClientCheckout | None = None ) -> Connection: """Get or create a Connection. Can raise ConnectionFailure.""" # We use the pid here to avoid issues with fork / multiprocessing. @@ -879,7 +879,7 @@ def checkin(self, conn: Connection) -> None: self._pinned_sockets.discard(conn) forked = self.pid != os.getpid() # Re-apply the accounting if a BaseException interrupts here (PYTHON-6074). - close_conn_reason: Optional[str] = None + close_conn_reason: str | None = None emit_closed = False accounted = False try: @@ -965,11 +965,11 @@ class _PoolCheckout: def __init__( self, pool: Pool, - handler: Optional[_ClientCheckout] = None, + handler: _ClientCheckout | None = None, ) -> None: self._pool = pool self._handler = handler - self._conn: Optional[Connection] = None + self._conn: Connection | None = None def __enter__(self) -> Connection: pool = self._pool @@ -995,9 +995,9 @@ def __enter__(self) -> Connection: def __exit__( self, - exc_type: Optional[type[BaseException]], - exc_val: Optional[BaseException], - exc_tb: Optional[TracebackType], + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: TracebackType | None, ) -> None: conn = self._conn if conn is None: diff --git a/pymongo/synchronous/server.py b/pymongo/synchronous/server.py index 0faed74f76..803cb0093c 100644 --- a/pymongo/synchronous/server.py +++ b/pymongo/synchronous/server.py @@ -19,7 +19,6 @@ from typing import ( TYPE_CHECKING, Any, - Optional, ) from pymongo._telemetry import _SdamTelemetry @@ -43,9 +42,9 @@ def __init__( server_description: ServerDescription, pool: Pool, monitor: Monitor, - topology_id: Optional[ObjectId] = None, - listeners: Optional[_EventListeners] = None, - events: Optional[ReferenceType[Queue[Any]]] = None, + topology_id: ObjectId | None = None, + listeners: _EventListeners | None = None, + events: ReferenceType[Queue[Any]] | None = None, ) -> None: """Represent one MongoDB server.""" self._description = server_description @@ -62,7 +61,7 @@ def open(self) -> None: if not self._pool.opts.load_balanced: self._monitor.open() - def reset(self, service_id: Optional[ObjectId] = None) -> None: + def reset(self, service_id: ObjectId | None = None) -> None: """Clear the connection pool.""" self.pool.reset(service_id) @@ -73,8 +72,12 @@ def close(self) -> None: """ self._sdam.server_closed(self._description.address) - self._monitor.close() - self._pool.close() + try: + self._monitor.close() + finally: + # The pool must close even if cancellation or an error + # interrupts the monitor close (PYTHON-6226). + self._pool.close() def request_check(self) -> None: """Check the server's state soon.""" diff --git a/pymongo/synchronous/settings.py b/pymongo/synchronous/settings.py index 3008471b25..372f6e7b83 100644 --- a/pymongo/synchronous/settings.py +++ b/pymongo/synchronous/settings.py @@ -18,16 +18,22 @@ import threading from collections.abc import Callable, Collection -from typing import Optional +from typing import TYPE_CHECKING -from bson.objectid import ObjectId from pymongo import common from pymongo.common import LOCAL_THRESHOLD_MS, SERVER_SELECTION_TIMEOUT -from pymongo.pool_options import PoolOptions from pymongo.settings_shared import _BaseTopologySettings from pymongo.synchronous import monitor, pool from pymongo.synchronous.pool import Pool -from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.pool_options import PoolOptions + from pymongo.topology_description import _ServerSelector + +if TYPE_CHECKING: + import threading + from collections.abc import Callable, Collection _IS_SYNC = True @@ -35,25 +41,25 @@ class TopologySettings(_BaseTopologySettings[type[Pool], type[monitor.Monitor]]): def __init__( self, - seeds: Optional[Collection[tuple[str, int]]] = None, - replica_set_name: Optional[str] = None, - pool_class: Optional[type[Pool]] = None, - pool_options: Optional[PoolOptions] = None, - monitor_class: Optional[type[monitor.Monitor]] = None, - condition_class: Optional[type[threading.Condition]] = None, + seeds: Collection[tuple[str, int]] | None = None, + replica_set_name: str | None = None, + pool_class: type[Pool] | None = None, + pool_options: PoolOptions | None = None, + monitor_class: type[monitor.Monitor] | None = None, + condition_class: type[threading.Condition] | None = None, local_threshold_ms: int = LOCAL_THRESHOLD_MS, server_selection_timeout: int = SERVER_SELECTION_TIMEOUT, heartbeat_frequency: int = common.HEARTBEAT_FREQUENCY, - server_selector: Optional[_ServerSelector] = None, - fqdn: Optional[str] = None, - direct_connection: Optional[bool] = False, - load_balanced: Optional[bool] = None, + server_selector: _ServerSelector | None = None, + fqdn: str | None = None, + direct_connection: bool | None = False, + load_balanced: bool | None = None, srv_service_name: str = common.SRV_SERVICE_NAME, srv_max_hosts: int = 0, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, server_monitoring_mode: str = common.SERVER_MONITORING_MODE, - topology_id: Optional[ObjectId] = None, + topology_id: ObjectId | None = None, ): """Represent MongoClient's configuration. diff --git a/pymongo/synchronous/srv_resolver.py b/pymongo/synchronous/srv_resolver.py index 3a20043654..774c36bb48 100644 --- a/pymongo/synchronous/srv_resolver.py +++ b/pymongo/synchronous/srv_resolver.py @@ -18,8 +18,7 @@ import ipaddress import random -from collections.abc import Callable -from typing import TYPE_CHECKING, Any, Optional, Union +from typing import TYPE_CHECKING, Any from pymongo._psl import SPECIAL_USE_LABELS, _to_punycode, is_public_suffix from pymongo._telemetry import log_srv_monitor_invalid_host @@ -27,6 +26,8 @@ from pymongo.errors import ConfigurationError if TYPE_CHECKING: + from collections.abc import Callable + from dns import resolver _IS_SYNC = True @@ -34,7 +35,7 @@ # dnspython can return bytes or str from various parts # of its API depending on version. We always want str. -def maybe_decode(text: Union[str, bytes]) -> str: +def maybe_decode(text: str | bytes) -> str: if isinstance(text, bytes): return text.decode() return text @@ -62,11 +63,11 @@ class _SrvResolver: def __init__( self, fqdn: str, - connect_timeout: Optional[float], + connect_timeout: float | None, srv_service_name: str, srv_max_hosts: int = 0, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ): self.__fqdn = fqdn.lower() self.__srv = srv_service_name @@ -113,7 +114,7 @@ def __init__( self.__slen = len(self.__plist) self.nparts = len(split_fqdn) - def get_options(self) -> Optional[str]: + def get_options(self) -> str | None: from dns import resolver try: diff --git a/pymongo/synchronous/topology.py b/pymongo/synchronous/topology.py index e767d9e061..b7a9bd366c 100644 --- a/pymongo/synchronous/topology.py +++ b/pymongo/synchronous/topology.py @@ -18,15 +18,13 @@ import asyncio import os -import queue import random import sys import time import warnings import weakref -from collections.abc import Callable, Mapping from pathlib import Path -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast from pymongo import _csot, common, helpers_shared, periodic_executor from pymongo._telemetry import ( @@ -73,6 +71,9 @@ ) if TYPE_CHECKING: + import queue + from collections.abc import Callable, Mapping + from pymongo.synchronous.settings import TopologySettings from pymongo.typings import _Address @@ -86,7 +87,7 @@ class Topology(_AgnosticTopologyBase[Pool, Server]): _settings: TopologySettings _events_executor: periodic_executor.PeriodicExecutor - _srv_monitor: Optional[SrvMonitor] + _srv_monitor: SrvMonitor | None _monitor_tasks: list[MonitorBase] def __init__(self, topology_settings: TopologySettings): @@ -162,10 +163,10 @@ def select_servers( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - operation_id: Optional[int] = None, - deprioritized_servers: Optional[list[Server]] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + operation_id: int | None = None, + deprioritized_servers: list[Server] | None = None, ) -> list[Server]: """Return a list of Servers matching selector, or time out. @@ -202,7 +203,7 @@ def select_servers( ) return [ - cast(Server, self.get_server_by_address(sd.address)) for sd in server_descriptions + cast("Server", self.get_server_by_address(sd.address)) for sd in server_descriptions ] def _select_servers_loop( @@ -210,16 +211,16 @@ def _select_servers_loop( selector: Callable[[Selection], Selection], timeout: float, operation: str, - operation_id: Optional[int], - address: Optional[_Address], - deprioritized_servers: Optional[list[Server]] = None, + operation_id: int | None, + address: _Address | None, + deprioritized_servers: list[Server] | None = None, ) -> list[ServerDescription]: """select_servers() guts. Hold the lock when calling this.""" now = time.monotonic() end_time = now + timeout logged_waiting = False # Server selection does not have APM events, gate only on logging - ss: Optional[_ServerSelectionTelemetry] = None + ss: _ServerSelectionTelemetry | None = None if _is_debug_enabled(_SERVER_SELECTION_LOGGER): ss = _ServerSelectionTelemetry( self._topology_id, selector, operation, operation_id, self.description @@ -269,10 +270,10 @@ def _select_server( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: servers = self.select_servers( selector, @@ -294,10 +295,10 @@ def select_server( self, selector: Callable[[Selection], Selection], operation: str, - server_selection_timeout: Optional[float] = None, - address: Optional[_Address] = None, - deprioritized_servers: Optional[list[Server]] = None, - operation_id: Optional[int] = None, + server_selection_timeout: float | None = None, + address: _Address | None = None, + deprioritized_servers: list[Server] | None = None, + operation_id: int | None = None, ) -> Server: """Like select_servers, but choose a random server if several match.""" server = self._select_server( @@ -326,8 +327,8 @@ def select_server_by_address( self, address: _Address, operation: str, - server_selection_timeout: Optional[int] = None, - operation_id: Optional[int] = None, + server_selection_timeout: int | None = None, + operation_id: int | None = None, ) -> Server: """Return a Server for "address", reconnecting if necessary. @@ -450,7 +451,7 @@ def on_srv_update(self, seedlist: list[tuple[str, Any]]) -> None: if self._opened: self._process_srv_update(seedlist) - def get_primary(self) -> Optional[_Address]: + def get_primary(self) -> _Address | None: """Return primary's address or None.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: @@ -481,7 +482,7 @@ def get_arbiters(self) -> set[_Address]: """Return set of arbiter addresses.""" return self._get_replica_set_members(arbiter_server_selector) - def receive_cluster_time(self, cluster_time: Optional[Mapping[str, Any]]) -> None: + def receive_cluster_time(self, cluster_time: Mapping[str, Any] | None) -> None: with self._lock: self._receive_cluster_time_no_lock(cluster_time) @@ -702,10 +703,13 @@ def _update_servers(self) -> None: for address, server in list(self._servers.items()): if not self._description.has_server(address): - server.close() + # Update our state before closing: close() can cancel the + # calling task, so the stale server must be recorded as + # removed before close() runs, not after (PYTHON-6226). if not _IS_SYNC: self._monitor_tasks.append(server._monitor) self._servers.pop(address) + server.close() def cleanup_monitors(self) -> None: tasks = [] diff --git a/pymongo/synchronous/uri_parser.py b/pymongo/synchronous/uri_parser.py index 9a7fcf0fae..2133795784 100644 --- a/pymongo/synchronous/uri_parser.py +++ b/pymongo/synchronous/uri_parser.py @@ -17,8 +17,7 @@ from __future__ import annotations -from collections.abc import Callable -from typing import Any, Optional +from typing import TYPE_CHECKING, Any from pymongo.common import SRV_SERVICE_NAME, _CaseInsensitiveDictionary from pymongo.errors import ConfigurationError, InvalidURI @@ -36,20 +35,23 @@ split_options, ) +if TYPE_CHECKING: + from collections.abc import Callable + _IS_SYNC = True def parse_uri( uri: str, - default_port: Optional[int] = DEFAULT_PORT, + default_port: int | None = DEFAULT_PORT, validate: bool = True, warn: bool = False, normalize: bool = True, - connect_timeout: Optional[float] = None, - srv_service_name: Optional[str] = None, - srv_max_hosts: Optional[int] = None, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + connect_timeout: float | None = None, + srv_service_name: str | None = None, + srv_max_hosts: int | None = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ) -> dict[str, Any]: """Parse and validate a MongoDB URI. @@ -128,15 +130,15 @@ def parse_uri( def _parse_srv( uri: str, - default_port: Optional[int] = DEFAULT_PORT, + default_port: int | None = DEFAULT_PORT, validate: bool = True, warn: bool = False, normalize: bool = True, - connect_timeout: Optional[float] = None, - srv_service_name: Optional[str] = None, - srv_max_hosts: Optional[int] = None, - srv_allowed_hosts_suffix: Optional[str] = None, - srv_host_validator: Optional[Callable[[str], bool]] = None, + connect_timeout: float | None = None, + srv_service_name: str | None = None, + srv_max_hosts: int | None = None, + srv_allowed_hosts_suffix: str | None = None, + srv_host_validator: Callable[[str], bool] | None = None, ) -> dict[str, Any]: if uri.startswith(SCHEME): is_srv = False diff --git a/pymongo/topology_description.py b/pymongo/topology_description.py index ab15e7d85a..af4619456b 100644 --- a/pymongo/topology_description.py +++ b/pymongo/topology_description.py @@ -22,21 +22,23 @@ from collections.abc import Callable, Mapping, MutableMapping from random import sample from typing import ( + TYPE_CHECKING, Any, NamedTuple, - Optional, cast, ) from bson.min_key import MinKey -from bson.objectid import ObjectId from pymongo import common from pymongo.errors import ConfigurationError, PyMongoError from pymongo.read_preferences import Primary, ReadPreference, _AggWritePref, _ServerMode from pymongo.server_description import ServerDescription from pymongo.server_selectors import Selection from pymongo.server_type import SERVER_TYPE -from pymongo.typings import _Address + +if TYPE_CHECKING: + from bson.objectid import ObjectId + from pymongo.typings import _Address # Enumeration for various kinds of MongoDB cluster topologies. @@ -63,9 +65,9 @@ def __init__( self, topology_type: int, server_descriptions: dict[_Address, ServerDescription], - replica_set_name: Optional[str], - max_set_version: Optional[int], - max_election_id: Optional[ObjectId], + replica_set_name: str | None, + max_set_version: int | None, + max_election_id: ObjectId | None, topology_settings: Any, ) -> None: """Representation of a deployment of MongoDB servers. @@ -184,9 +186,7 @@ def reset(self) -> TopologyDescription: ) def server_descriptions(self) -> dict[_Address, ServerDescription]: - """dict of (address, - :class:`~pymongo.server_description.ServerDescription`). - """ + """Return a dict of (address, :class:`~pymongo.server_description.ServerDescription`).""" return self._server_descriptions.copy() @property @@ -203,22 +203,22 @@ def topology_type_name(self) -> str: return TOPOLOGY_TYPE._fields[self._topology_type] @property - def replica_set_name(self) -> Optional[str]: + def replica_set_name(self) -> str | None: """The replica set name.""" return self._replica_set_name @property - def max_set_version(self) -> Optional[int]: + def max_set_version(self) -> int | None: """Greatest setVersion seen from a primary, or None.""" return self._max_set_version @property - def max_election_id(self) -> Optional[ObjectId]: + def max_election_id(self) -> ObjectId | None: """Greatest electionId seen from a primary, or None.""" return self._max_election_id @property - def logical_session_timeout_minutes(self) -> Optional[int]: + def logical_session_timeout_minutes(self) -> int | None: """Minimum logical session timeout, or None.""" return self._ls_timeout_minutes @@ -243,7 +243,7 @@ def candidate_servers(self) -> list[ServerDescription]: return self._candidate_servers @property - def common_wire_version(self) -> Optional[int]: + def common_wire_version(self) -> int | None: """Minimum of all servers' max wire versions, or None.""" servers = self.known_servers if servers: @@ -259,7 +259,7 @@ def heartbeat_frequency(self) -> int: def srv_max_hosts(self) -> int: return self._topology_settings._srv_max_hosts - def _apply_local_threshold(self, selection: Optional[Selection]) -> list[ServerDescription]: + def _apply_local_threshold(self, selection: Selection | None) -> list[ServerDescription]: if not selection: return [] round_trip_times: list[float] = [] @@ -274,12 +274,10 @@ def _apply_local_threshold(self, selection: Optional[Selection]) -> list[ServerD return [ s for s in selection.server_descriptions - if (cast(float, s.round_trip_time) - fastest) <= threshold + if (cast("float", s.round_trip_time) - fastest) <= threshold ] - def _filter_servers( - self, deprioritized_servers: Optional[list[ServerDescription]] = None - ) -> None: + def _filter_servers(self, deprioritized_servers: list[ServerDescription] | None = None) -> None: """Filter out deprioritized servers from a list of server candidates.""" if not deprioritized_servers: self._candidate_servers = self.known_servers @@ -295,9 +293,9 @@ def _filter_servers( def apply_selector( self, selector: Any, - address: Optional[_Address] = None, - custom_selector: Optional[_ServerSelector] = None, - deprioritized_servers: Optional[list[ServerDescription]] = None, + address: _Address | None = None, + custom_selector: _ServerSelector | None = None, + deprioritized_servers: list[ServerDescription] | None = None, ) -> list[ServerDescription]: """List of servers matching the provided selector(s). @@ -562,11 +560,11 @@ def _updated_topology_description_srv_polling( def _update_rs_from_primary( sds: MutableMapping[_Address, ServerDescription], - replica_set_name: Optional[str], + replica_set_name: str | None, server_description: ServerDescription, - max_set_version: Optional[int], - max_election_id: Optional[ObjectId], -) -> tuple[int, Optional[str], Optional[int], Optional[ObjectId]]: + max_set_version: int | None, + max_election_id: ObjectId | None, +) -> tuple[int, str | None, int | None, ObjectId | None]: """Update topology description from a primary's hello response. Pass in a dict of ServerDescriptions, current replica set name, the @@ -650,7 +648,7 @@ def _update_rs_from_primary( def _update_rs_with_primary_from_member( sds: MutableMapping[_Address, ServerDescription], - replica_set_name: Optional[str], + replica_set_name: str | None, server_description: ServerDescription, ) -> int: """RS with known primary. Process a response from a non-primary. @@ -673,9 +671,9 @@ def _update_rs_with_primary_from_member( def _update_rs_no_primary_from_member( sds: MutableMapping[_Address, ServerDescription], - replica_set_name: Optional[str], + replica_set_name: str | None, server_description: ServerDescription, -) -> tuple[int, Optional[str]]: +) -> tuple[int, str | None]: """RS without known primary. Update from a non-primary's response. Pass in a dict of ServerDescriptions, current replica set name, and the diff --git a/pymongo/topology_shared.py b/pymongo/topology_shared.py index 23e47557db..ce5bd5f9a8 100644 --- a/pymongo/topology_shared.py +++ b/pymongo/topology_shared.py @@ -17,9 +17,7 @@ from __future__ import annotations import queue -import weakref -from collections.abc import Callable, Mapping -from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar +from typing import TYPE_CHECKING, Any, Generic, TypeVar from pymongo import _csot from pymongo._telemetry import _SdamTelemetry @@ -29,6 +27,9 @@ from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription if TYPE_CHECKING: + import weakref + from collections.abc import Callable, Mapping + from bson import ObjectId from pymongo.server_description import ServerDescription from pymongo.settings_shared import _BaseTopologySettings @@ -64,7 +65,7 @@ def __init__( max_wire_version: int, sock_generation: int, completed_handshake: bool, - service_id: Optional[ObjectId], + service_id: ObjectId | None, ): self.error = error self.max_wire_version = max_wire_version @@ -74,7 +75,7 @@ def __init__( def _is_stale_error_topology_version( - current_tv: Optional[Mapping[str, Any]], error_tv: Optional[Mapping[str, Any]] + current_tv: Mapping[str, Any] | None, error_tv: Mapping[str, Any] | None ) -> bool: """Return True if the error's topologyVersion is <= current.""" if current_tv is None or error_tv is None: @@ -137,8 +138,8 @@ def __init__(self, topology_settings: _BaseTopologySettings[Any, Any]) -> None: self._opened = False self._closed = False self._servers: dict[_Address, _ServerT] = {} - self._pid: Optional[int] = None - self._max_cluster_time: Optional[ClusterTime] = None + self._pid: int | None = None + self._max_cluster_time: ClusterTime | None = None self._session_pool = _ServerSessionPool() # The lock, condition, events executor, SRV monitor, and monitor tasks # are IO-specific and are created by the async/sync subclasses. @@ -153,7 +154,7 @@ def get_server_selection_timeout(self) -> float: return self._settings.server_selection_timeout return timeout - def get_server_by_address(self, address: _Address) -> Optional[_ServerT]: + def get_server_by_address(self, address: _Address) -> _ServerT | None: """Get a Server or None. Returns the current version of the server immediately, even if it's @@ -166,11 +167,11 @@ def get_server_by_address(self, address: _Address) -> Optional[_ServerT]: def has_server(self, address: _Address) -> bool: return address in self._servers - def max_cluster_time(self) -> Optional[ClusterTime]: + def max_cluster_time(self) -> ClusterTime | None: """Return a document, the highest seen $clusterTime.""" return self._max_cluster_time - def _receive_cluster_time_no_lock(self, cluster_time: Optional[Mapping[str, Any]]) -> None: + def _receive_cluster_time_no_lock(self, cluster_time: Mapping[str, Any] | None) -> None: # Driver Sessions Spec: "Whenever a driver receives a cluster time from # a server it MUST compare it to the current highest seen cluster time # for the deployment. If the new cluster time is higher than the @@ -202,7 +203,7 @@ def pop_all_sessions(self) -> list[_ServerSession]: """Pop all session ids from the pool.""" return self._session_pool.pop_all() - def get_server_session(self, session_timeout_minutes: Optional[int]) -> _ServerSession: + def get_server_session(self, session_timeout_minutes: int | None) -> _ServerSession: """Start or resume a server session, or raise ConfigurationError.""" return self._session_pool.get_server_session(session_timeout_minutes) @@ -329,7 +330,7 @@ def __repr__(self) -> str: msg = "CLOSED " return f"<{self.__class__.__name__} {msg}{self._description!r}>" - def eq_props(self) -> tuple[tuple[_Address, ...], Optional[str], Optional[str], str]: + def eq_props(self) -> tuple[tuple[_Address, ...], str | None, str | None, str]: """The properties to use for MongoClient/AsyncMongoClient and Topology equality checks. """ diff --git a/pymongo/typings.py b/pymongo/typings.py index aae4fbe7f5..aca6fd7da8 100644 --- a/pymongo/typings.py +++ b/pymongo/typings.py @@ -20,7 +20,6 @@ from typing import ( TYPE_CHECKING, Any, - Optional, TypeVar, Union, ) @@ -49,7 +48,7 @@ # Common Shared Types. -_Address = tuple[str, Optional[int]] +_Address = tuple[str, int | None] _CollationIn = Union[Mapping[str, Any], "Collation"] _Pipeline = Sequence[Mapping[str, Any]] ClusterTime = Mapping[str, Any] @@ -68,7 +67,7 @@ _AgnosticClientBulk = Union["_AsyncClientBulk", "_ClientBulk"] -def strip_optional(elem: Optional[_T]) -> _T: +def strip_optional(elem: _T | None) -> _T: """This function is to allow us to cast all the elements of an iterator from Optional[_T] to _T while inside a list comprehension. """ diff --git a/pymongo/uri_parser_shared.py b/pymongo/uri_parser_shared.py index 5e34c2d702..f4af8c20fc 100644 --- a/pymongo/uri_parser_shared.py +++ b/pymongo/uri_parser_shared.py @@ -23,12 +23,9 @@ import re import sys import warnings -from collections.abc import Mapping, MutableMapping, Sized from typing import ( TYPE_CHECKING, Any, - Optional, - Union, cast, ) from urllib.parse import unquote_plus @@ -41,10 +38,12 @@ get_validated_options, ) from pymongo.errors import ConfigurationError, InvalidURI -from pymongo.typings import _Address if TYPE_CHECKING: + from collections.abc import Mapping, MutableMapping, Sized + from pymongo.pyopenssl_context import SSLContext + from pymongo.typings import _Address SCHEME = "mongodb://" @@ -155,9 +154,7 @@ def parse_userinfo(userinfo: str) -> tuple[str, str]: return unquote_plus(user), unquote_plus(passwd) -def parse_ipv6_literal_host( - entity: str, default_port: Optional[int] -) -> tuple[str, Optional[Union[str, int]]]: +def parse_ipv6_literal_host(entity: str, default_port: int | None) -> tuple[str, str | int | None]: """Validates an IPv6 literal host:port string. Returns a 2-tuple of IPv6 literal followed by port where @@ -178,7 +175,7 @@ def parse_ipv6_literal_host( return entity[1:i], entity[i + 2 :] -def parse_host(entity: str, default_port: Optional[int] = DEFAULT_PORT) -> _Address: +def parse_host(entity: str, default_port: int | None = DEFAULT_PORT) -> _Address: """Validates a host string Returns a 2-tuple of host followed by port where port is default_port @@ -190,7 +187,7 @@ def parse_host(entity: str, default_port: Optional[int] = DEFAULT_PORT) -> _Addr specified in entity. """ host = entity - port: Optional[Union[str, int]] = default_port + port: str | int | None = default_port if entity[0] == "[": host, port = parse_ipv6_literal_host(entity, default_port) elif entity.endswith(".sock"): @@ -237,7 +234,7 @@ def parse_host(entity: str, default_port: Optional[int] = DEFAULT_PORT) -> _Addr } -def _parse_options(opts: str, delim: Optional[str]) -> _CaseInsensitiveDictionary: +def _parse_options(opts: str, delim: str | None) -> _CaseInsensitiveDictionary: """Helper method for split_options which creates the options dict. Also handles the creation of a list for the URI tag_sets/ readpreferencetags portion, and the use of a unicode options string. @@ -426,14 +423,14 @@ def split_options( options = _normalize_options(options) if validate: - options = cast(_CaseInsensitiveDictionary, validate_options(options, warn)) + options = cast("_CaseInsensitiveDictionary", validate_options(options, warn)) if options.get("authsource") == "": raise InvalidURI("the authSource database cannot be an empty string") return options -def split_hosts(hosts: str, default_port: Optional[int] = DEFAULT_PORT) -> list[_Address]: +def split_hosts(hosts: str, default_port: int | None = DEFAULT_PORT) -> list[_Address]: """Takes a string of the form host1[:port],host2[:port]... and splits it into (host, port) tuples. If [:port] isn't present the default_port is used. @@ -494,7 +491,7 @@ def _check_options(nodes: Sized, options: Mapping[str, Any]) -> None: def _parse_kms_tls_options( - kms_tls_options: Optional[Mapping[str, Any]], + kms_tls_options: Mapping[str, Any] | None, is_sync: bool, ) -> dict[str, SSLContext]: """Parse KMS TLS connection options.""" @@ -510,7 +507,7 @@ def _parse_kms_tls_options( opts = _CaseInsensitiveDictionary(options) opts = _handle_security_options(opts) opts = _normalize_options(opts) - opts = cast(_CaseInsensitiveDictionary, validate_options(opts)) + opts = cast("_CaseInsensitiveDictionary", validate_options(opts)) ssl_context, allow_invalid_hostnames = _parse_ssl_options(opts, is_sync) if ssl_context is None: raise ConfigurationError("TLS is required for KMS providers") @@ -531,11 +528,11 @@ def _parse_kms_tls_options( def _validate_uri( uri: str, - default_port: Optional[int] = DEFAULT_PORT, + default_port: int | None = DEFAULT_PORT, validate: bool = True, warn: bool = False, normalize: bool = True, - srv_max_hosts: Optional[int] = None, + srv_max_hosts: int | None = None, ) -> dict[str, Any]: if uri.startswith(SCHEME): is_srv = False @@ -634,6 +631,5 @@ def _make_options_case_sensitive(options: _CaseInsensitiveDictionary) -> dict[st if option.lower() in options: case_sensitive[option] = options[option] options.pop(option) - for k, v in options.items(): - case_sensitive[k] = v + case_sensitive.update(options) return case_sensitive diff --git a/pymongo/write_concern.py b/pymongo/write_concern.py index 6f3731849f..8b0450d722 100644 --- a/pymongo/write_concern.py +++ b/pymongo/write_concern.py @@ -19,7 +19,7 @@ from __future__ import annotations -from typing import Any, Optional, Union +from typing import Any from pymongo.errors import ConfigurationError @@ -65,10 +65,10 @@ class WriteConcern: def __init__( self, - w: Optional[Union[int, str]] = None, - wtimeout: Optional[int] = None, - j: Optional[bool] = None, - fsync: Optional[bool] = None, + w: int | str | None = None, + wtimeout: int | None = None, + j: bool | None = None, + fsync: bool | None = None, ) -> None: self.__document: dict[str, Any] = {} self.__acknowledged = True @@ -131,14 +131,14 @@ def __repr__(self) -> str: ", ".join(f"{k}={v!r}" for k, v in self.__document.items()) ) - def __eq__(self, other: Any) -> bool: + def __eq__(self, other: object) -> bool: if isinstance(other, WriteConcern): return self.__document == other.document return NotImplemented __hash__ = None # type: ignore[assignment] - def __ne__(self, other: Any) -> bool: + def __ne__(self, other: object) -> bool: if isinstance(other, WriteConcern): return self.__document != other.document return NotImplemented diff --git a/pyproject.toml b/pyproject.toml index b4f3e282c2..baac84b775 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,20 +44,10 @@ Documentation = "https://www.mongodb.com/docs/languages/python/pymongo-driver/cu Source = "https://github.com/mongodb/mongo-python-driver" Tracker = "https://jira.mongodb.org/projects/PYTHON/issues" -[tool.uv] -# Pin the uv binary version across local dev, GitHub Actions, and Evergreen. -# uv enforces this locally, astral-sh/setup-uv reads it on GitHub, and -# install-dependencies.sh installs it in Evergreen. Bump manually when a newer uv -# is needed. -required-version = "==0.12.12" -# Skip dependency releases newer than 7 days. Defining it here keeps every uv -# invocation on the same cutoff. -exclude-newer = "7 days" - [dependency-groups] dev = [] lint = [ - "ruff==0.15.20", + "ruff==0.17.3", ] unasync = [ {include-group = "lint"}, @@ -71,7 +61,7 @@ coverage = [ mockupdb = [ "mockupdb>=1.8.1" ] -# Atheris publishes CPython 3.12-3.14 Linux x86_64 wheels only; see fuzz/README.md. +# The latest atheris publishes CPython 3.12-3.14 Linux x86_64 wheels only; see fuzz/README.md. fuzz = ["atheris>=2.3.0"] perf = ["simplejson>=3.17.0"] typing = [ @@ -195,7 +185,7 @@ line-length = 100 extend-exclude = ["drivers-evergreen-tools"] [tool.ruff.lint] -select = [ +extend-select = [ "E", "F", "W", # flake8 "B", # flake8-bugbear "I", # isort @@ -218,11 +208,16 @@ select = [ "YTT", # flake8-2020 "EXE", # flake8-executable "ASYNC", # flake8-async + "TC", # flake8-type-checking + "PERF", # perflint + "D202", # pydocstyle: no blank lines between docstring and function body. + "D209", # pydocstyle: closing quotes go on their own line. + "D301", # pydocstyle: docstrings containing \ are defined as string literals. + "D403", # pydocstyle: docstrings start with a capital letter. ] ignore = [ "PLR", # Design related pylint codes "E501", # Line too long - "UP007", # Use `X | Y` for type annotation "EM101", # Exception must not use a string literal, assign to variable first "EM102", # Exception must not use an f-string literal, assign to variable first "G004", # Logging statement uses f-string" @@ -241,13 +236,12 @@ ignore = [ "EM103", # Exception must not use a `.format()` string directly, assign to variable first "C408", # Unnecessary `dict` call (rewrite as a literal) "SIM117", # Use a single `with` statement with multiple contexts instead of nested `with` statements - "UP045", # Use `X | Y` for union annotation (Enable when we drop 3.9 support) "PLC0415", # `import` should be at the top-level of a file - "UP041", # `asyncio.TimeoutError` is an alias of `TimeoutError` on 3.11+ "ASYNC109", # Async function with a `timeout` parameter (CSOT timeouts are not `asyncio.timeout`) "UP042", # `str, Enum` should be `StrEnum` (changes `__str__` semantics) "UP017", # `timezone.utc` preferred over `datetime.UTC` (keep existing style) - "B905", # `zip()` without an explicit `strict=` parameter + "ICN001", # Use standard import naming conventions (pandas as pd, datetime as dt...) + "BLE", # Broad `Except` exception catches (intentional) ] unfixable = [ "RUF100", # Unused noqa @@ -258,19 +252,21 @@ exclude = [] flake8-unused-arguments.ignore-variadic-names = true isort.required-imports = ["from __future__ import annotations"] dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?)|dummy.*)$" +pydocstyle.convention = "pep257" [tool.ruff.lint.per-file-ignores] "pymongo/__init__.py" = ["E402"] ".evergreen/scripts/*.py" = ["T201"] -".evergreen/scripts/setup-uv.py" = ["I002"] +".evergreen/scripts/setup_uv.py" = ["I002"] "test/*.py" = ["PT", "E402", "PLW", "SIM", "E741", "PTH", "S", "B904", "E722", "T201", "RET", "ARG", "F405", "B028", "PGH001", "B018", "F403", "RUF015", "E731", "B007", - "UP031", "F401", "B023", "F811"] + "UP031", "F401", "B023", "F811", "DTZ002", "LOG"] "tools/*.py" = ["T201"] "tools/test_*.py" = ["E402", "S"] "fuzz/*.py" = ["T201", "E402"] "hatch_build.py" = ["S"] "_setup.py" = ["SIM112"] +"pymongo/event_loggers.py" = ["LOG"] [tool.coverage.run] branch = true diff --git a/requirements/encryption.txt b/requirements/encryption.txt index 10aa1db198..46bc17225b 100644 --- a/requirements/encryption.txt +++ b/requirements/encryption.txt @@ -1,3 +1,3 @@ pymongo-auth-aws>=1.3.0,<2.0.0 -pymongocrypt>=1.18.1,<2.0.0 +pymongocrypt>=1.21.0,<2.0.0 certifi>=2023.7.22;os.name=='nt' or sys_platform=='darwin' diff --git a/test/__init__.py b/test/__init__.py index 2220bf3661..5a2a5d7ea3 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -43,10 +43,9 @@ HAVE_IPADDRESS = True except ImportError: HAVE_IPADDRESS = False -from collections.abc import Callable, Generator from contextlib import contextmanager from functools import partial, wraps -from typing import Any, overload +from typing import TYPE_CHECKING, Any, overload from unittest import SkipTest from urllib.parse import quote_plus @@ -57,7 +56,6 @@ from pymongo.hello import HelloCompat from pymongo.server_api import ServerApi from pymongo.ssl_support import HAVE_SSL, _ssl # type:ignore[attr-defined] -from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient sys.path[0:0] = [""] @@ -84,6 +82,11 @@ ) from test.version import Version +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from pymongo.synchronous.database import Database + _IS_SYNC = True @@ -784,6 +787,18 @@ def require_exhaust_cursors(self, func): func=func, ) + def require_exhaust_stream(self, func): + """Run a test only if the server streams exhaust getMores. + + mongos streams exhaust getMores from 7.1 (SERVER-57297); older + mongos reply per batch, so the receive-only state is never reached. + """ + return self._require( + lambda: not (self.is_mongos or self.load_balancer) or self.version.at_least(7, 1), + "Exhaust streams require mongos 7.1+", + func=func, + ) + def supports_transactions(self): return self.is_mongos or self.is_rs diff --git a/test/asynchronous/__init__.py b/test/asynchronous/__init__.py index 57ee8e9a99..62d684cd76 100644 --- a/test/asynchronous/__init__.py +++ b/test/asynchronous/__init__.py @@ -43,17 +43,15 @@ HAVE_IPADDRESS = True except ImportError: HAVE_IPADDRESS = False -from collections.abc import Callable, Generator from contextlib import asynccontextmanager, contextmanager from functools import partial, wraps -from typing import Any, overload +from typing import TYPE_CHECKING, Any, overload from unittest import SkipTest from urllib.parse import quote_plus import pymongo import pymongo.errors from bson.son import SON -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.common import partition_node from pymongo.hello import HelloCompat @@ -84,6 +82,11 @@ ) from test.version import Version +if TYPE_CHECKING: + from collections.abc import Callable, Generator + + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False @@ -784,6 +787,18 @@ def require_exhaust_cursors(self, func): func=func, ) + def require_exhaust_stream(self, func): + """Run a test only if the server streams exhaust getMores. + + mongos streams exhaust getMores from 7.1 (SERVER-57297); older + mongos reply per batch, so the receive-only state is never reached. + """ + return self._require( + lambda: not (self.is_mongos or self.load_balancer) or self.version.at_least(7, 1), + "Exhaust streams require mongos 7.1+", + func=func, + ) + def supports_transactions(self): return self.is_mongos or self.is_rs diff --git a/test/asynchronous/helpers.py b/test/asynchronous/helpers.py index bbce967767..a75668c48d 100644 --- a/test/asynchronous/helpers.py +++ b/test/asynchronous/helpers.py @@ -113,7 +113,7 @@ def __del__(self): f"EVENTS_QUEUE_FREQUENCY={common.EVENTS_QUEUE_FREQUENCY}, stack:\n{self._stack}" ) self.disable() - raise Exception(msg) + raise RuntimeError(msg) # Global knobs to speed up the test suite. @@ -141,7 +141,7 @@ def __init__(self, **kwargs): async def start(self): self.task = asyncio.create_task(self.run(), name=self.name) - async def join(self, timeout: Optional[float] = None): # type: ignore[override] + async def join(self, timeout: float | None = None): # type: ignore[override] if self.task is not None: await asyncio.wait([self.task], timeout=timeout) diff --git a/test/asynchronous/test_async_loop_unblocked.py b/test/asynchronous/test_async_loop_unblocked.py index 7f3f97ae44..65b8027d62 100644 --- a/test/asynchronous/test_async_loop_unblocked.py +++ b/test/asynchronous/test_async_loop_unblocked.py @@ -51,7 +51,7 @@ async def background_task(): await t self.assertLessEqual( - sorted(latencies, reverse=True)[0], + max(latencies), 1.0, "Background task was blocked from running", ) diff --git a/test/asynchronous/test_async_network_layer.py b/test/asynchronous/test_async_network_layer.py index ad146e1e79..96abf34240 100644 --- a/test/asynchronous/test_async_network_layer.py +++ b/test/asynchronous/test_async_network_layer.py @@ -265,7 +265,7 @@ def slow(arg): time.sleep(0.4) finished.set() - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await _async_blocking_socket_call(asyncio.get_running_loop(), slow, None, 0.3) self.assertTrue(finished.is_set()) diff --git a/test/asynchronous/test_auth.py b/test/asynchronous/test_auth.py index 72085d62dd..02aaa326c6 100644 --- a/test/asynchronous/test_auth.py +++ b/test/asynchronous/test_auth.py @@ -239,9 +239,7 @@ async def test_gssapi_threaded(self): except OperationFailure: raise SkipTest("User must be able to write.") - threads = [] - for _ in range(4): - threads.append(AutoAuthenticateThread(collection)) + threads = [AutoAuthenticateThread(collection) for _ in range(4)] for thread in threads: thread.start() for thread in threads: @@ -661,9 +659,7 @@ async def test_scram_threaded(self): # The first thread to call find() will authenticate client = await self.async_rs_or_single_client() coll = client.db.coll - threads = [] - for _ in range(4): - threads.append(AutoAuthenticateThread(coll)) + threads = [AutoAuthenticateThread(coll) for _ in range(4)] for thread in threads: thread.start() for thread in threads: diff --git a/test/asynchronous/test_auth_oidc.py b/test/asynchronous/test_auth_oidc.py index 66f4309eba..12cb69eac2 100644 --- a/test/asynchronous/test_auth_oidc.py +++ b/test/asynchronous/test_auth_oidc.py @@ -314,7 +314,7 @@ def fetch(self, ctx): client = await self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() # Close the client. await client.close() @@ -558,7 +558,7 @@ def fetch(self, a): return None client = await self.create_client(request_cb=RequestTokenNull()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() await client.close() @@ -568,7 +568,7 @@ def fetch(self, a): return {} client = await self.create_client(request_cb=CallbackInvalidToken()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() await client.close() @@ -826,9 +826,7 @@ async def target(): for _ in range(100): await client.test.coll.find_one() - tasks = [] - for i in range(10): - tasks.append(ConcurrentRunner(target=target)) + tasks = [ConcurrentRunner(target=target) for _ in range(10)] for t in tasks: await t.start() for t in tasks: @@ -852,7 +850,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() async def test_2_3_oidc_callback_returns_missing_data(self): @@ -866,7 +864,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() async def test_2_4_invalid_client_configuration_with_callback(self): diff --git a/test/asynchronous/test_bulk.py b/test/asynchronous/test_bulk.py index 5c6bbc9764..907f837d57 100644 --- a/test/asynchronous/test_bulk.py +++ b/test/asynchronous/test_bulk.py @@ -18,16 +18,13 @@ import sys import uuid -from typing import Any, Optional - -from pymongo.asynchronous.mongo_client import AsyncMongoClient +from typing import TYPE_CHECKING, Any sys.path[0:0] = [""] from bson.binary import Binary, UuidRepresentation from bson.codec_options import CodecOptions from bson.objectid import ObjectId -from pymongo.asynchronous.collection import AsyncCollection from pymongo.common import partition_node from pymongo.errors import BulkWriteError, ConfigurationError, InvalidOperation, OperationFailure from pymongo.operations import * @@ -35,6 +32,10 @@ from test.asynchronous import AsyncIntegrationTest, async_client_context, remove_all_users, unittest from test.utils_shared import async_wait_until +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False @@ -63,7 +64,7 @@ def assertEqualResponse(self, expected, actual): % (len(expected_upserts), len(actual_upserts)), ) - for e, a in zip(expected_upserts, actual_upserts): + for e, a in zip(expected_upserts, actual_upserts, strict=True): self.assertEqualUpsert(e, a) elif key == "writeErrors": @@ -76,7 +77,7 @@ def assertEqualResponse(self, expected, actual): % (len(expected_errors), len(actual_errors)), ) - for e, a in zip(expected_errors, actual_errors): + for e, a in zip(expected_errors, actual_errors, strict=True): self.assertEqualWriteError(e, a) else: @@ -309,8 +310,7 @@ async def test_bulk_max_message_size(self): {"_id": 3, "l": "s" * (_16_MB - 10000)}, ] # Fill in the remaining ~10000 bytes with small documents. - for i in range(4, 10000): - docs.append({"_id": i}) + docs.extend({"_id": i} for i in range(4, 10000)) result = await self.coll.insert_many(docs) self.assertEqual(len(docs), len(result.inserted_ids)) @@ -924,7 +924,7 @@ async def test_no_remove(self): class AsyncTestBulkWriteConcern(AsyncBulkTestBase): - w: Optional[int] + w: int | None secondary: AsyncMongoClient async def asyncSetUp(self): diff --git a/test/asynchronous/test_change_stream.py b/test/asynchronous/test_change_stream.py index 6b1b7b4cb9..a2cfa8c67a 100644 --- a/test/asynchronous/test_change_stream.py +++ b/test/asynchronous/test_change_stream.py @@ -90,9 +90,7 @@ async def generate_invalidate_event(self, change_stream): def generate_unique_collnames(self, numcolls): """Generate numcolls collection names unique to a test.""" - collnames = [] - for idx in range(1, numcolls + 1): - collnames.append(self.id() + "_" + str(idx)) + collnames = [self.id() + "_" + str(idx) for idx in range(1, numcolls + 1)] return collnames async def get_resume_token(self, invalidate=False): @@ -1090,7 +1088,7 @@ def assert_list_contents_are_subset(self, superlist, sublist): element in superlist. """ self.assertEqual(len(superlist), len(sublist)) - for sup, sub in zip(superlist, sublist): + for sup, sub in zip(superlist, sublist, strict=True): if isinstance(sub, dict): self.assert_dict_is_subset(sup, sub) continue diff --git a/test/asynchronous/test_client.py b/test/asynchronous/test_client.py index 2b61dda182..73b8417226 100644 --- a/test/asynchronous/test_client.py +++ b/test/asynchronous/test_client.py @@ -860,7 +860,7 @@ def test_detected_environment_logging(self, mock_get_hosts): @skipIf(os.environ.get("DEBUG_LOG"), "Enabling debug logs breaks this test") @patch("pymongo.asynchronous.srv_resolver._SrvResolver.get_hosts") async def test_detected_environment_warning(self, mock_get_hosts): - with self._caplog.at_level(logging.WARN): + with self._caplog.at_level(logging.WARNING): normal_hosts = [ "host.cosmos.azure.com", "host.docdb.amazonaws.com", @@ -1318,7 +1318,7 @@ async def test_list_databases(self): self.assertGreater(len(helper_docs), 0) self.assertEqual(len(helper_docs), len(cmd_docs)) # PYTHON-3529 Some fields may change between calls, just compare names. - for helper_doc, cmd_doc in zip(helper_docs, cmd_docs): + for helper_doc, cmd_doc in zip(helper_docs, cmd_docs, strict=True): self.assertIs(type(helper_doc), dict) self.assertEqual(helper_doc.keys(), cmd_doc.keys()) client = await self.async_rs_or_single_client(document_class=SON) @@ -2236,7 +2236,7 @@ async def test_background_connections_log_on_error(self): pool = await async_get_pool(client) async def fail_connect(*args, **kwargs): - raise Exception("failed to connect") + raise ConnectionFailure("failed to connect") pool.connect = fail_connect # Un-patch Pool.connect to break the cyclic reference. diff --git a/test/asynchronous/test_client_backpressure.py b/test/asynchronous/test_client_backpressure.py index ecba937717..54f0a6699d 100644 --- a/test/asynchronous/test_client_backpressure.py +++ b/test/asynchronous/test_client_backpressure.py @@ -22,7 +22,9 @@ from time import perf_counter from unittest.mock import patch +from pymongo import AsyncMongoClient from pymongo.common import MAX_ADAPTIVE_RETRIES +from pymongo.cursor_shared import CursorType sys.path[0:0] = [""] @@ -162,6 +164,95 @@ async def test_retry_overload_error_getMore(self): self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) + @async_client_context.require_failCommand_appName + async def test_retry_overload_error_getMore_pinned_connection(self): + # PYTHON-6262: getMores on pinned (e.g. load-balanced) connections must + # retry retryable overload errors on the pinned connection. + coll = self.db.coll + await coll.delete_many({}) + await coll.insert_many([{"x": 1} for _ in range(10)]) + fail_many = { + "configureFailPoint": "failCommand", + "mode": {"times": MAX_ADAPTIVE_RETRIES}, + "data": { + "failCommands": ["getMore"], + "errorCode": 462, # IngressRequestRateLimitExceeded + "errorLabels": ["RetryableError", "SystemOverloadedError"], + }, + } + with patch.object(type(self.db.client), "_should_pin_cursor", return_value=True): + # Ensure pinned getMore is retried on overload error. + cursor = coll.find(batch_size=2) + await cursor.next() + # Verify the cursor actually pinned its connection. + self.assertIsNotNone(cursor._sock_mgr) + async with self.fail_point(fail_many): + self.assertEqual(len(await cursor.to_list()), 9) + + # Ensure pinned getMore stops retrying after MAX_ADAPTIVE_RETRIES. + fail_too_many = fail_many.copy() + fail_too_many["mode"] = {"times": MAX_ADAPTIVE_RETRIES + 1} + cursor = coll.find(batch_size=2) + await cursor.next() + async with self.fail_point(fail_too_many): + with self.assertRaises(PyMongoError) as error: + await cursor.to_list() + + self.assertIn("RetryableError", str(error.exception)) + self.assertIn("SystemOverloadedError", str(error.exception)) + + @async_client_context.require_failCommand_appName + @async_client_context.require_exhaust_stream + async def test_retry_overload_error_getMore_exhaust_receive_only(self): + # PYTHON-6262: an error on a receive-only exhaust getMore must + # surface instead of retrying a receive with no request in flight. + # Use a dedicated client: the abandoned exhaust stream leaves the + # pinned connection unusable. + uri = await async_client_context.uri + client = AsyncMongoClient( + uri, server_api=async_client_context.default_client_options.get("server_api") + ) + self.addAsyncCleanup(client.close) + coll = client.get_database(self.db.name).coll + await coll.delete_many({}) + await coll.insert_many([{"x": 1} for _ in range(10)]) + with patch.object(type(client), "_should_pin_cursor", return_value=True): + cursor = coll.find(batch_size=2, cursor_type=CursorType.EXHAUST) + for _ in range(4): + await cursor.next() + if cursor._sock_mgr and cursor._sock_mgr.more_to_come: + break + self.assertTrue(cursor._sock_mgr.more_to_come) + conn = cursor._sock_mgr.conn + orig_receive = type(conn).receive_message + receives = 0 + + async def fail_receive_only(conn, request_id): + # Consume the streamed reply, then fail like a retryable + # overload reply would. + reply = await orig_receive(conn, request_id) + if request_id is None: + nonlocal receives + receives += 1 + raise OperationFailure( + "getMore overload", + 462, + { + "errorLabels": ["RetryableError", "SystemOverloadedError"], + "baseBackoffMS": 10, + }, + ) + return reply + + with patch.object(type(conn), "receive_message", fail_receive_only): + with self.assertRaises(PyMongoError) as error: + await cursor.to_list() + + # The failed receive ended the stream: no request-less retry. + self.assertEqual(receives, 1) + self.assertIn("RetryableError", str(error.exception)) + self.assertIn("SystemOverloadedError", str(error.exception)) + # Prose tests. class AsyncTestClientBackpressure(AsyncIntegrationTest): diff --git a/test/asynchronous/test_client_bulk_write.py b/test/asynchronous/test_client_bulk_write.py index 85236a2346..0ec667467b 100644 --- a/test/asynchronous/test_client_bulk_write.py +++ b/test/asynchronous/test_client_bulk_write.py @@ -98,18 +98,18 @@ async def test_3_batch_splits_if_num_operations_too_large(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append(InsertOne(namespace="db.coll", document={"a": "b"})) + models = [ + InsertOne(namespace="db.coll", document={"a": "b"}) + for _ in range(self.max_write_batch_size + 1) + ] self.addAsyncCleanup(client.db["coll"].drop) result = await client.bulk_write(models=models) self.assertEqual(result.inserted_count, self.max_write_batch_size + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -122,25 +122,23 @@ async def test_4_batch_splits_if_ops_payload_too_large(self): listener = OvertCommandListener() client = await self.async_rs_or_single_client(event_listeners=[listener]) - models = [] num_models = int(self.max_message_size_bytes / self.max_bson_object_size + 1) b_repeated = "b" * (self.max_bson_object_size - 500) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] self.addAsyncCleanup(client.db["coll"].drop) result = await client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -166,14 +164,13 @@ async def test_5_collects_write_concern_errors_across_batches(self): }, } async with self.fail_point(fail_command): - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"a": "b"}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": "b"}, ) + for _ in range(self.max_write_batch_size + 1) + ] self.addAsyncCleanup(client.db["coll"].drop) with self.assertRaises(ClientBulkWriteException) as context: @@ -184,10 +181,9 @@ async def test_5_collects_write_concern_errors_across_batches(self): context.exception.partial_result.inserted_count, self.max_write_batch_size + 1 ) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) @async_client_context.require_version_min(8, 0, 0, -24) @@ -200,23 +196,21 @@ async def test_6_collects_write_errors_across_batches_unordered(self): await collection.drop() await collection.insert_one(document={"_id": 1}) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"_id": 1}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"_id": 1}, ) + for _ in range(self.max_write_batch_size + 1) + ] with self.assertRaises(ClientBulkWriteException) as context: await client.bulk_write(models=models, ordered=False) self.assertEqual(len(context.exception.write_errors), self.max_write_batch_size + 1) # type: ignore[arg-type] - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) @async_client_context.require_version_min(8, 0, 0, -24) @@ -229,23 +223,21 @@ async def test_6_collects_write_errors_across_batches_ordered(self): await collection.drop() await collection.insert_one(document={"_id": 1}) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"_id": 1}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"_id": 1}, ) + for _ in range(self.max_write_batch_size + 1) + ] with self.assertRaises(ClientBulkWriteException) as context: await client.bulk_write(models=models, ordered=True) self.assertEqual(len(context.exception.write_errors), 1) # type: ignore[arg-type] - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 1) @async_client_context.require_version_min(8, 0, 0, -24) @@ -422,15 +414,14 @@ async def _setup_namespace_test_models(self): num_models = ops_bytes // self.max_bson_object_size remainder_bytes = ops_bytes % self.max_bson_object_size - models = [] b_repeated = "b" * (self.max_bson_object_size - _OPERATION_DOC_BYTES) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] if remainder_bytes >= _NAMESPACE_DOC_BYTES: num_models += 1 b_repeated = "b" * (remainder_bytes - _OPERATION_DOC_BYTES) @@ -460,10 +451,9 @@ async def test_11_no_batch_splits_if_new_namespace_is_not_too_large(self): result = await client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 1) event = bulk_write_events[0] @@ -493,10 +483,9 @@ async def test_11_batch_splits_if_new_namespace_is_too_large(self): result = await client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -652,16 +641,15 @@ async def test_timeout_in_multi_batch_bulk_write(self): "data": {"failCommands": ["bulkWrite"], "blockConnection": True, "blockTimeMS": 1010}, } async with self.fail_point(fail_command): - models = [] num_models = int(self.max_message_size_bytes / self.max_bson_object_size + 1) b_repeated = "b" * (self.max_bson_object_size - _OVERHEAD) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] listener = OvertCommandListener() client = await self.async_rs_or_single_client( @@ -678,8 +666,7 @@ async def test_timeout_in_multi_batch_bulk_write(self): await client.bulk_write(models=models) self.assertIsInstance(context.exception.error, NetworkTimeout) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) diff --git a/test/asynchronous/test_client_metadata.py b/test/asynchronous/test_client_metadata.py index a0438fb72a..3d8d0660cf 100644 --- a/test/asynchronous/test_client_metadata.py +++ b/test/asynchronous/test_client_metadata.py @@ -18,17 +18,19 @@ import pathlib import time import unittest -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast import pytest -from pymongo import AsyncMongoClient from pymongo.driver_info import DriverInfo from pymongo.monitoring import ConnectionClosedEvent from test.asynchronous import AsyncIntegrationTest from test.asynchronous.unified_format import generate_test_classes, get_test_path from test.utils_shared import CMAPListener +if TYPE_CHECKING: + from pymongo import AsyncMongoClient + try: from mockupdb import MockupDB, OpMsgReply @@ -67,10 +69,10 @@ def respond(r): async def send_ping_and_get_metadata( self, client: AsyncMongoClient, is_handshake: bool - ) -> tuple[str, Optional[str], Optional[str], dict[str, Any]]: + ) -> tuple[str, str | None, str | None, dict[str, Any]]: # reset if handshake request if is_handshake: - self.handshake_req: Optional[dict] = None + self.handshake_req: dict | None = None await client.admin.command("ping") metadata = _get_handshake_driver_info(self.handshake_req) @@ -86,8 +88,8 @@ async def check_metadata_added( self, client: AsyncMongoClient, add_name: str, - add_version: Optional[str], - add_platform: Optional[str], + add_version: str | None, + add_platform: str | None, ) -> None: # send initial metadata name, version, platform, metadata = await self.send_ping_and_get_metadata(client, True) @@ -196,7 +198,7 @@ async def test_doesnt_update_established_connections(self): add_name, add_version, add_platform = "framework", "2.0", "Framework Platform" client.append_metadata(DriverInfo(add_name, add_version, add_platform)) # check new data isn't sent - self.handshake_req: Optional[dict] = None + self.handshake_req: dict | None = None await client.admin.command("ping") self.assertIsNone(self.handshake_req) self.assertEqual(listener.event_count(ConnectionClosedEvent), 0) @@ -295,11 +297,11 @@ async def test_10_entries_in_driver_name_and_driver_version_correspond_by_index( self.assertIsNotNone(name0) self.assertIsNotNone(version0) - version0 = cast(str, version0) + version0 = cast("str", version0) driver_name = name0.split("|")[0] driver_version = version0.split("|")[0] - def resolve(value: Optional[str]) -> Optional[str]: + def resolve(value: str | None) -> str | None: if value is None: return None return value.format(driver_name=driver_name, driver_version=driver_version) diff --git a/test/asynchronous/test_collection.py b/test/asynchronous/test_collection.py index d63952cbe2..5c378d9bf0 100644 --- a/test/asynchronous/test_collection.py +++ b/test/asynchronous/test_collection.py @@ -23,9 +23,8 @@ from codecs import utf_8_decode from collections import defaultdict from collections.abc import Iterable -from typing import Any, no_type_check +from typing import TYPE_CHECKING, Any, no_type_check -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.helpers import anext from test.asynchronous.utils import async_get_pool @@ -40,7 +39,6 @@ from pymongo import ASCENDING, DESCENDING, GEO2D, GEOSPHERE, HASHED, TEXT from pymongo.asynchronous.collection import AsyncCollection, ReturnDocument from pymongo.asynchronous.command_cursor import AsyncCommandCursor -from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.bulk_shared import BulkWriteError from pymongo.cursor_shared import CursorType from pymongo.errors import ( @@ -79,6 +77,10 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False @@ -504,7 +506,7 @@ async def test_index_2dsphere(self): await db.coll.drop_indexes() self.assertEqual("geo_2dsphere", await db.coll.create_index([("geo", GEOSPHERE)])) - for dummy, info in (await db.coll.index_information()).items(): + for info in (await db.coll.index_information()).values(): field, idx_type = info["key"][0] if field == "geo" and idx_type == "2dsphere": break @@ -523,7 +525,7 @@ async def test_index_hashed(self): await db.coll.drop_indexes() self.assertEqual("a_hashed", await db.coll.create_index([("a", HASHED)])) - for dummy, info in (await db.coll.index_information()).items(): + for info in (await db.coll.index_information()).values(): field, idx_type = info["key"][0] if field == "a" and idx_type == "hashed": break diff --git a/test/asynchronous/test_comment.py b/test/asynchronous/test_comment.py index c681170482..c57f08ae6e 100644 --- a/test/asynchronous/test_comment.py +++ b/test/asynchronous/test_comment.py @@ -55,7 +55,7 @@ async def _test_ops( "signature of function %s" % (h.__name__), ) self.assertEqual( - inspect.signature(h).parameters["comment"].annotation, "Optional[Any]" + inspect.signature(h).parameters["comment"].annotation, "Any | None" ) if isinstance(maybe_cursor, AsyncCommandCursor): await maybe_cursor.close() diff --git a/test/asynchronous/test_concurrency.py b/test/asynchronous/test_concurrency.py index a3588d6848..ebb5218318 100644 --- a/test/asynchronous/test_concurrency.py +++ b/test/asynchronous/test_concurrency.py @@ -37,7 +37,6 @@ async def _task(self, client): "PYTHON-5861: $where is too slow on macOS CI", ) async def test_concurrency(self): - tasks = [] iterations = 5 client = await self.async_single_client() @@ -52,8 +51,7 @@ async def test_concurrency(self): sequential_time = time.time() - start start = time.time() - for i in range(iterations): - tasks.append(self._task(client)) + tasks = [self._task(client) for _ in range(iterations)] await asyncio.gather(*tasks) concurrent_time = time.time() - start diff --git a/test/asynchronous/test_connection_monitoring.py b/test/asynchronous/test_connection_monitoring.py index c9399be48e..48fc08de28 100644 --- a/test/asynchronous/test_connection_monitoring.py +++ b/test/asynchronous/test_connection_monitoring.py @@ -199,7 +199,7 @@ def actual_events(self, ignore): def check_events(self, events, ignore): """Check the events of a test.""" actual_events = self.actual_events(ignore) - for actual, expected in zip(actual_events, events): + for actual, expected in zip(actual_events, events, strict=False): self.logs.append(f"Checking event actual: {actual!r} vs expected: {expected!r}") self.check_event(actual, expected) diff --git a/test/asynchronous/test_connections_survive_primary_stepdown_spec.py b/test/asynchronous/test_connections_survive_primary_stepdown_spec.py index f3b729316e..889605c594 100644 --- a/test/asynchronous/test_connections_survive_primary_stepdown_spec.py +++ b/test/asynchronous/test_connections_survive_primary_stepdown_spec.py @@ -22,9 +22,10 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson import SON from pymongo import monitoring -from pymongo.asynchronous.collection import AsyncCollection from pymongo.errors import NotPrimaryError from pymongo.write_concern import WriteConcern from test.asynchronous import ( @@ -37,6 +38,9 @@ CMAPListener, ) +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + _IS_SYNC = False diff --git a/test/asynchronous/test_cursor.py b/test/asynchronous/test_cursor.py index 364f4eb946..178b08bc6a 100644 --- a/test/asynchronous/test_cursor.py +++ b/test/asynchronous/test_cursor.py @@ -26,7 +26,7 @@ import sys import threading import time -from typing import Any +from typing import TYPE_CHECKING, Any import pymongo @@ -40,7 +40,6 @@ from pymongo.asynchronous.helpers import anext from pymongo.collation import Collation from pymongo.errors import ExecutionTimeout, InvalidOperation, OperationFailure, PyMongoError -from pymongo.operations import _IndexList from pymongo.read_concern import ReadConcern from pymongo.read_preferences import ReadPreference from pymongo.write_concern import WriteConcern @@ -55,6 +54,9 @@ ignore_deprecations, ) +if TYPE_CHECKING: + from pymongo.operations import _IndexList + _IS_SYNC = False @@ -1037,18 +1039,18 @@ def test_getitem_slice_index(self): self.assertRaises(IndexError, lambda: self.db.coll.find()[-1:]) self.assertRaises(IndexError, lambda: self.db.coll.find()[1:2:2]) - for a, b in zip(count(0), self.db.coll.find()): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find(), strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(100, len(list(self.db.coll.find()[0:]))) # type: ignore[call-overload] - for a, b in zip(count(0), self.db.coll.find()[0:]): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()[0:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for a, b in zip(count(99), self.db.coll.find()[99:]): # type: ignore[call-overload] + for a, b in zip(count(99), self.db.coll.find()[99:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) for _i in self.db.coll.find()[1000:]: @@ -1056,19 +1058,19 @@ def test_getitem_slice_index(self): self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[20:25]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:25], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[40:45][20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[40:45][20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45][20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20), strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(1, len(list(self.db.coll.find()[:1]))) # type: ignore[call-overload] diff --git a/test/asynchronous/test_custom_types.py b/test/asynchronous/test_custom_types.py index 34c4d05650..4fb4717e0f 100644 --- a/test/asynchronous/test_custom_types.py +++ b/test/asynchronous/test_custom_types.py @@ -145,9 +145,7 @@ def test_encode_decode_roundtrip(self): @no_type_check def test_decode_all(self): - documents = [] - for dec in range(3): - documents.append({"average": Decimal(f"56.4{dec}")}) + documents = [{"average": Decimal(f"56.4{dec}")} for dec in range(3)] bsonstream = b"" for doc in documents: @@ -181,7 +179,9 @@ def _generate_multidocument_bson_stream(self): @no_type_check def test_decode_iter(self): expected, bson_data = self._generate_multidocument_bson_stream() - for expected_doc, decoded_doc in zip(expected, decode_iter(bson_data, self.codecopts)): + for expected_doc, decoded_doc in zip( + expected, decode_iter(bson_data, self.codecopts), strict=True + ): self.assertEqual(expected_doc, decoded_doc) @no_type_check @@ -191,7 +191,9 @@ def test_decode_file_iter(self): fileobj.write(bson_data) fileobj.seek(0) - for expected_doc, decoded_doc in zip(expected, decode_file_iter(fileobj, self.codecopts)): + for expected_doc, decoded_doc in zip( + expected, decode_file_iter(fileobj, self.codecopts), strict=True + ): self.assertEqual(expected_doc, decoded_doc) fileobj.close() diff --git a/test/asynchronous/test_database.py b/test/asynchronous/test_database.py index bbca8ff19a..1a67ddbcb1 100644 --- a/test/asynchronous/test_database.py +++ b/test/asynchronous/test_database.py @@ -19,7 +19,7 @@ import re import sys from collections.abc import Iterable, Mapping -from typing import Any, Union +from typing import Any from pymongo.asynchronous.command_cursor import AsyncCommandCursor @@ -212,7 +212,7 @@ async def test_list_collection_names_filter(self): await db.capped.insert_one({}) await db.non_capped.insert_one({}) self.addAsyncCleanup(client.drop_database, db.name) - filter: Union[None, Mapping[str, Any]] + filter: Mapping[str, Any] | None # Should not send nameOnly. for filter in ({"options.capped": True}, {"options.capped": True, "name": "capped"}): listener.reset() @@ -487,7 +487,7 @@ async def test_id_ordering(self): ) cursor = db.coll.find() async for x in cursor: - for k, _v in x.items(): + for k in x.keys(): self.assertEqual(k, "_id") break diff --git a/test/asynchronous/test_discovery_and_monitoring.py b/test/asynchronous/test_discovery_and_monitoring.py index a3129812b1..e686dd1926 100644 --- a/test/asynchronous/test_discovery_and_monitoring.py +++ b/test/asynchronous/test_discovery_and_monitoring.py @@ -20,11 +20,14 @@ import os import platform import socketserver +import struct import sys import threading import time +import unittest from asyncio import StreamReader, StreamWriter from pathlib import Path +from typing import Any from pymongo.asynchronous.pool import AsyncConnection from pymongo.errors import ConnectionFailure @@ -38,6 +41,8 @@ from unittest.mock import patch from bson import Timestamp, json_util +from bson import decode as bson_decode +from bson import encode as bson_encode from pymongo import common, monitoring from pymongo.asynchronous.settings import TopologySettings from pymongo.asynchronous.topology import Topology @@ -58,7 +63,7 @@ ServerHeartbeatStartedEvent, ) from pymongo.server_description import SERVER_TYPE, ServerDescription -from pymongo.topology_description import TOPOLOGY_TYPE +from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription from pymongo.topology_shared import _ErrorContext from test.asynchronous import ( AsyncIntegrationTest, @@ -350,9 +355,7 @@ async def insert_command(i): except AutoReconnect: pass - tasks = [] - for i in range(N_TASKS): - tasks.append(ConcurrentRunner(target=insert_command, args=(i,))) + tasks = [ConcurrentRunner(target=insert_command, args=(i,)) for i in range(N_TASKS)] for t in tasks: await t.start() for t in tasks: @@ -533,9 +536,7 @@ async def target(): pass # Run 100 parallel operations that contend for connections. - tasks = [] - for _ in range(100): - tasks.append(ConcurrentRunner(target=target)) + tasks = [ConcurrentRunner(target=target) for _ in range(100)] for t in tasks: await t.start() for t in tasks: @@ -556,7 +557,7 @@ async def test_rtt_connection_is_enabled_stream(self): await client.admin.command("ping") def predicate(): - for _, server in client._topology._servers.items(): + for server in client._topology._servers.values(): monitor = server._monitor if not monitor._stream: return False @@ -598,7 +599,7 @@ async def test_rtt_connection_is_disabled_auto(self): async def assert_rtt_connection_is_disabled(self, client): await client.admin.command("ping") - for _, server in client._topology._servers.items(): + for server in client._topology._servers.values(): monitor = server._monitor self.assertFalse(monitor._stream) if _IS_SYNC: @@ -679,6 +680,156 @@ async def handle_client(reader: StreamReader, writer: StreamWriter): ) +class TestMonitorRecoversAfterSelfRemoval(AsyncUnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: monitor task self-cancellation is async-only") + async def test_monitor_recovers_after_self_removal(self): + # Regression test for PYTHON-6226: a monitor that closed its own + # server used to cancel itself, leaving the client stuck in + # ReplicaSetNoPrimary. The client must recover. + + # Fake two-node replica set on ephemeral ports. + role: dict[int, str] = {} + hosts: list[str] = [] + + def make_handler(port_box): + async def handle(reader: StreamReader, writer: StreamWriter): + port = port_box["port"] + try: + while True: + length, req_id, _, _ = struct.unpack( + # The ignore is for the sync mirror, where + # unasync turns this read into a bare call. + " dict[str, StringOpts]: - """Pass StringOpts under the name the installed pymongocrypt accepts. - - pymongocrypt renamed ``text_opts`` to ``string_opts`` in 1.19 and takes only - one of the two, and the preview query types still run against pymongocrypt - before 1.19, so both spellings are in play across the matrix. - """ - return {encryption._string_opts_kwarg(): StringOpts(**kwargs)} - - -class TestStringOptsDeprecation(AsyncPyMongoTestCase): - def test_text_opts_is_still_re_exported(self): - # TextOpts is deprecated, not removed, so it must stay importable from - # the encryption module for the deprecation period. - self.assertIs(encryption.TextOpts, TextOpts) - - def test_text_opts_is_deprecated(self): - with self.assertWarns(DeprecationWarning): - opts = TextOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - self.assertIsInstance(opts, StringOpts) - self.assertEqual( - StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}).document, - opts.document, - ) - - def test_resolve_string_opts_no_opts(self): - self.assertIsNone(encryption._resolve_string_opts(None, None)) - - def test_resolve_string_opts_rejects_both(self): - string_opts = StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - with self.assertRaises(ConfigurationError): - encryption._resolve_string_opts(string_opts, string_opts) - - @unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed") - def test_resolve_string_opts_follows_pymongocrypt(self): - # pymongocrypt accepts only one of the two names per release: text_opts - # through 1.18 and string_opts from 1.19. Passing the name the - # installed binding does not support is an error rather than a silent - # alias, so assert against the resolved name. - string_opts = StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - if encryption._string_opts_kwarg() == "string_opts": - supported, unsupported = (string_opts, None), (None, string_opts) - else: - supported, unsupported = (None, string_opts), (string_opts, None) - self.assertIs(encryption._resolve_string_opts(*supported), string_opts) - with self.assertRaises(ConfigurationError): - encryption._resolve_string_opts(*unsupported) - - @unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed") - def test_string_opts_kwarg_matches_binding(self): - # The resolved name is passed straight through to pymongocrypt, so - # assert it against the installed binding here: a mismatch then fails - # without a server, rather than only in the prose suite. - params = inspect.signature(encryption.AsyncExplicitEncrypter.encrypt).parameters - self.assertIn(encryption._string_opts_kwarg(), params) - - class AsyncEncryptionIntegrationTest(AsyncIntegrationTest): """Base class for encryption integration tests.""" @@ -323,8 +267,8 @@ def create_client_encryption( key_vault_namespace: str, key_vault_client: AsyncMongoClient, codec_options: CodecOptions, - kms_tls_options: Optional[Mapping[str, Any]] = None, - kms_connect_callback: Optional[Any] = None, + kms_tls_options: Mapping[str, Any] | None = None, + kms_connect_callback: Any | None = None, ): client_encryption = AsyncClientEncryption( kms_providers, @@ -344,8 +288,8 @@ def unmanaged_create_client_encryption( key_vault_namespace: str, key_vault_client: AsyncMongoClient, codec_options: CodecOptions, - kms_tls_options: Optional[Mapping[str, Any]] = None, - kms_connect_callback: Optional[Any] = None, + kms_tls_options: Mapping[str, Any] | None = None, + kms_connect_callback: Any | None = None, ): client_encryption = AsyncClientEncryption( kms_providers, @@ -1451,7 +1395,7 @@ async def _test_explicit(self, expectation): await self._setup() client_encryption = self.create_client_encryption( self.KMS_PROVIDER_MAP, # type: ignore[arg-type] - ".".join([self.KEYVAULT_DB, self.KEYVAULT_COLL]), + f"{self.KEYVAULT_DB}.{self.KEYVAULT_COLL}", async_client_context.client, OPTS, ) @@ -1469,7 +1413,7 @@ async def _test_automatic(self, expectation_extjson, payload): await self._setup() encrypted_db = "db" encrypted_coll = "coll" - keyvault_namespace = ".".join([self.KEYVAULT_DB, self.KEYVAULT_COLL]) + keyvault_namespace = f"{self.KEYVAULT_DB}.{self.KEYVAULT_COLL}" encryption_opts = AutoEncryptionOpts( self.KMS_PROVIDER_MAP, # type: ignore[arg-type] @@ -2908,7 +2852,7 @@ async def run_expression_find( await self.encrypted_client.db.explicit_encryption.find(find_payload).to_list(), key=lambda x: x["_id"], ) - for elem, expected in zip(sorted_find, expected_elems): + for elem, expected in zip(sorted_find, expected_elems, strict=True): self.assertEqual(elem[f"encrypted{name}"], expected) async def run_test_cases(self, name, range_opts, cast_func): @@ -3313,6 +3257,7 @@ async def test_mixed_null_keyids(self): for val, key in zip( ["123-45-6789", "11/22/1963", "My secret", "New Mexico, 87104"], [field["keyId"] for field in ef["fields"]], + strict=True, ) ] await coll.insert_one( @@ -3409,43 +3354,30 @@ def _libmongocrypt_at_least(*version): return Version.from_string(libmongocrypt_version()) >= Version(*version) -# The minimum libmongocrypt version required by each string query type, declared -# in one place so the test gates and the changelog agree. Support landed per -# query type rather than all at once (see the libmongocrypt changelog): -# 1.18.1 - fixes caseSensitive/diacriticSensitive handling for "textPreview". -# 1.19.0 - the "string" algorithm replaces "textPreview"; prefix and suffix go -# stable; prefixPreview and suffixPreview are removed. -# 1.19.1 - prefixPreview and suffixPreview are restored. +# The minimum libmongocrypt version required by each GA string query type, +# declared in one place so the test gates and the changelog agree. Support +# landed per query type rather than all at once (see the libmongocrypt +# changelog): +# 1.19.0 - the "string" algorithm replaces "textPreview"; prefix and suffix +# go stable. # 1.20.0 - substring goes stable. +# 1.21.0 - the beta prefixPreview/suffixPreview/substringPreview query types +# became a runtime error (MONGOCRYPT-938) and were dropped in +# PYTHON-5959. _STRING_QUERY_MIN_LIBMONGOCRYPT = { "prefix": (1, 19, 0), "suffix": (1, 19, 0), "substring": (1, 20, 0), - "prefixPreview": (1, 18, 1), - "suffixPreview": (1, 18, 1), - "substringPreview": (1, 18, 1), } -# prefixPreview and suffixPreview were removed in 1.19.0 and restored in 1.19.1, -# so that one release is a hole rather than a floor. -_PREVIEW_REMOVED_IN = (1, 19, 0) - -# No pymongocrypt release ships libmongocrypt 1.19.0+, so the GA query types can -# only run against a master build; setup_tests.py pins the released binding for -# the 8.x preview tasks alone. Do not collapse that gate: the released binding -# still spells the parameter text_opts, and dropping back to it would silently -# stop exercising the GA path. - # https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.md#27-string-explicit-encryption class TestStringExplicitEncryptionProse(AsyncEncryptionIntegrationTest): - # The GA collections require server 9.0+, the preview collections require - # server pre-9.0. Setup encrypts with the "String" algorithm on 9.0+ and the - # deprecated "textPreview" algorithm on earlier servers, since "String" was - # only introduced in libmongocrypt 1.19.0. + # The GA collections require server 9.0+, where the "String" algorithm and + # the GA query types are supported. @async_client_context.require_no_standalone - @async_client_context.require_version_min(8, 2, -1) - @async_client_context.require_libmongocrypt_min(1, 18, 1) + @async_client_context.require_version_min(9, 0, -1) + @async_client_context.require_libmongocrypt_min(1, 19, 0) @async_client_context.require_pymongocrypt_min(1, 16, 0) async def asyncSetUp(self): await super().asyncSetUp() @@ -3481,39 +3413,18 @@ async def asyncSetUp(self): ) ) - # The GA query types ("prefix", "suffix", "substring") require server - # 9.0+, which in turn dropped the preview query types. - self.is_ga = async_client_context.version.at_least(9, 0, -1) - # The "String" algorithm was added in libmongocrypt 1.19.0. Servers - # before 9.0 are tested against libmongocrypt 1.18.x, where the preview - # query types are only usable via the deprecated "textPreview" - # algorithm, so pick whichever the running combination supports. - self.algorithm = ( - Algorithm.STRING if _libmongocrypt_at_least(1, 19, 0) else Algorithm.TEXTPREVIEW - ) - # The GA query types need the "String" algorithm, so skip before setup - # encrypts anything rather than erroring on an unsupported combination. - if self.is_ga and not _libmongocrypt_at_least(1, 19, 0): - raise unittest.SkipTest("server 9.0+ string queries require libmongocrypt 1.19.0+") # Substring went stable in a later libmongocrypt than prefix and suffix, # so its fixture is only built where the query type exists. Otherwise # setup would fail before the substring cases could skip, taking the # prefix and suffix cases down with it. - self.has_substring = _libmongocrypt_at_least( - *_STRING_QUERY_MIN_LIBMONGOCRYPT["substring" if self.is_ga else "substringPreview"] - ) + self.has_substring = _libmongocrypt_at_least(*_STRING_QUERY_MIN_LIBMONGOCRYPT["substring"]) # Using QE CreateCollection() and Collection.Drop(), drop and create the # collections with majority write concern. db = self.client_encrypted.db - if self.is_ga: - collections = ["prefix-suffix", "prefix-suffix-ci-di"] - if self.has_substring: - collections += ["substring", "substring-ci-di"] - else: - collections = ["prefix-suffix-preview"] - if self.has_substring: - collections += ["substring-preview"] + collections = ["prefix-suffix", "prefix-suffix-ci-di"] + if self.has_substring: + collections += ["substring", "substring-ci-di"] for name in collections: await db.drop_collection(name) await self.client_encryption.create_encrypted_collection( @@ -3527,9 +3438,9 @@ async def asyncSetUp(self): encrypted_value = await self.client_encryption.encrypt( "foobarbaz", key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, contention_factor=0, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), @@ -3537,33 +3448,25 @@ async def asyncSetUp(self): ), ) # Use explicitEncryptedClient to insert the following document into - # db.prefix-suffix (if created) and db.prefix-suffix-preview (if created) - # with majority write concern. - await self._insert( - "prefix-suffix" if self.is_ga else "prefix-suffix-preview", - {"_id": 0, "encryptedText": encrypted_value}, - ) + # db.prefix-suffix with majority write concern. + await self._insert("prefix-suffix", {"_id": 0, "encryptedText": encrypted_value}) if self.has_substring: # Use clientEncryption to encrypt the string "foobarbaz" with the following EncryptOpts. encrypted_value = await self.client_encryption.encrypt( "foobarbaz", key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, contention_factor=0, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ), ) # Use explicitEncryptedClient to insert the following document into - # db.substring (if created) and db.substring-preview (if created) with - # majority write concern. - await self._insert( - "substring" if self.is_ga else "substring-preview", - {"_id": 0, "encryptedText": encrypted_value}, - ) + # db.substring with majority write concern. + await self._insert("substring", {"_id": 0, "encryptedText": encrypted_value}) async def _insert(self, collection, document, client=None): """Insert a document with majority write concern.""" @@ -3578,45 +3481,15 @@ def _require_query_type(self, query_type): raise unittest.SkipTest( f"queryType={query_type} requires libmongocrypt {'.'.join(map(str, required))}+" ) - if query_type in ("prefixPreview", "suffixPreview") and ( - _libmongocrypt_at_least(*_PREVIEW_REMOVED_IN) and not _libmongocrypt_at_least(1, 19, 1) - ): - raise unittest.SkipTest(f"queryType={query_type} was removed in libmongocrypt 1.19.0") - - def _params(self, kind): - """Return the (query_type, collection) pair to run a case against. - - Each case runs against the GA query type on server 9.0+ and against the - preview query type on earlier servers, skipping when the installed - libmongocrypt is too old for the applicable variant. - """ - base = "substring" if kind == "substring" else "prefix-suffix" - if self.is_ga: - query_type, collection = kind, base - else: - query_type, collection = f"{kind}Preview", f"{base}-preview" - self._require_query_type(query_type) - return query_type, collection - - def _require_ga(self, *query_types): - """Skip a case that only applies to the GA query types. - - Gates on each query type the case exercises, since substring support - landed in a later libmongocrypt than prefix and suffix. - """ - if not self.is_ga: - raise unittest.SkipTest("requires server 9.0+") - for query_type in query_types: - self._require_query_type(query_type) async def _encrypt(self, value, query_type=None, **string_opts): return await self.client_encryption.encrypt( value, key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, query_type=query_type, contention_factor=0, - **_string_opts_kwargs(**string_opts), + string_opts=StringOpts(**string_opts), ) async def _find(self, collection, filter): @@ -3626,18 +3499,19 @@ async def _find(self, collection, filter): return value async def test_01_can_find_a_document_by_prefix(self): - query_type, collection = self._params("prefix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "foo". encrypted_value = await self._encrypt( "foo", - query_type=query_type, + query_type=QueryType.PREFIX, case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "prefix-suffix", { "$expr": { "$encStrStartsWith": {"input": "$encryptedText", "prefix": encrypted_value} @@ -3648,36 +3522,38 @@ async def test_01_can_find_a_document_by_prefix(self): self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) async def test_02_can_find_a_document_by_suffix(self): - query_type, collection = self._params("suffix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("suffix") # Use clientEncryption.encrypt() to encrypt the string "baz". encrypted_value = await self._encrypt( "baz", - query_type=query_type, + query_type=QueryType.SUFFIX, case_sensitive=True, diacritic_sensitive=True, suffix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "prefix-suffix", {"$expr": {"$encStrEndsWith": {"input": "$encryptedText", "suffix": encrypted_value}}}, ) # Assert the following document is returned. self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) async def test_03_no_document_found_by_prefix(self): - query_type, collection = self._params("prefix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "baz". encrypted_value = await self._encrypt( "baz", - query_type=query_type, + query_type=QueryType.PREFIX, case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "prefix-suffix", { "$expr": { "$encStrStartsWith": {"input": "$encryptedText", "prefix": encrypted_value} @@ -3688,36 +3564,38 @@ async def test_03_no_document_found_by_prefix(self): self.assertIsNone(value) async def test_04_no_document_found_by_suffix(self): - query_type, collection = self._params("suffix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("suffix") # Use clientEncryption.encrypt() to encrypt the string "foo". encrypted_value = await self._encrypt( "foo", - query_type=query_type, + query_type=QueryType.SUFFIX, case_sensitive=True, diacritic_sensitive=True, suffix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "prefix-suffix", {"$expr": {"$encStrEndsWith": {"input": "$encryptedText", "suffix": encrypted_value}}}, ) # Assert that no documents are returned. self.assertIsNone(value) async def test_05_can_find_a_document_by_substring(self): - query_type, collection = self._params("substring") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.20.0+. + self._require_query_type("substring") # Use clientEncryption.encrypt() to encrypt the string "bar". encrypted_value = await self._encrypt( "bar", - query_type=query_type, + query_type=QueryType.SUBSTRING, case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "substring", { "$expr": { "$encStrContains": {"input": "$encryptedText", "substring": encrypted_value} @@ -3728,18 +3606,19 @@ async def test_05_can_find_a_document_by_substring(self): self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) async def test_06_no_document_found_by_substring(self): - query_type, collection = self._params("substring") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.20.0+. + self._require_query_type("substring") # Use clientEncryption.encrypt() to encrypt the string "qux". encrypted_value = await self._encrypt( "qux", - query_type=query_type, + query_type=QueryType.SUBSTRING, case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = await self._find( - collection, + "substring", { "$expr": { "$encStrContains": {"input": "$encryptedText", "substring": encrypted_value} @@ -3752,7 +3631,7 @@ async def test_06_no_document_found_by_substring(self): async def test_07_contentionFactor_is_required(self): from pymongocrypt.errors import MongoCryptError - self._require_ga("prefix") + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "foo" without contentionFactor. with self.assertRaises(EncryptionError) as ctx: await self.client_encryption.encrypt( @@ -3760,7 +3639,7 @@ async def test_07_contentionFactor_is_required(self): key_id=self.key1_id, algorithm=Algorithm.STRING, query_type=QueryType.PREFIX, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), @@ -3773,7 +3652,8 @@ async def test_07_contentionFactor_is_required(self): async def test_08_case_insensitive_prefix_and_suffix(self): # This is a regression test for DRIVERS-3470. - self._require_ga("prefix", "suffix") + self._require_query_type("prefix") + self._require_query_type("suffix") # Use autoEncryptedClient to insert the following document. await self._insert( "prefix-suffix-ci-di", {"encryptedText": "BingQiLin"}, self.client_auto_encrypted @@ -3816,7 +3696,8 @@ async def test_08_case_insensitive_prefix_and_suffix(self): async def test_09_diacritic_insensitive_prefix_and_suffix(self): # This is a regression test for DRIVERS-3470. - self._require_ga("prefix", "suffix") + self._require_query_type("prefix") + self._require_query_type("suffix") # Use autoEncryptedClient to insert the following document. await self._insert( "prefix-suffix-ci-di", {"encryptedText": "cafébarbäz"}, self.client_auto_encrypted @@ -3859,7 +3740,7 @@ async def test_09_diacritic_insensitive_prefix_and_suffix(self): async def test_10_case_insensitive_substring(self): # This is a regression test for DRIVERS-3470. - self._require_ga("substring") + self._require_query_type("substring") # Use autoEncryptedClient to insert the following document. await self._insert( "substring-ci-di", {"encryptedText": "FooBarBaz"}, self.client_auto_encrypted @@ -3886,7 +3767,7 @@ async def test_10_case_insensitive_substring(self): async def test_11_diacritic_insensitive_substring(self): # This is a regression test for DRIVERS-3470. - self._require_ga("substring") + self._require_query_type("substring") # Use autoEncryptedClient to insert the following document. await self._insert( "substring-ci-di", {"encryptedText": "foocafébaz"}, self.client_auto_encrypted diff --git a/test/asynchronous/test_examples.py b/test/asynchronous/test_examples.py index 6a6d6b3d9e..35e0171a86 100644 --- a/test/asynchronous/test_examples.py +++ b/test/asynchronous/test_examples.py @@ -1113,7 +1113,7 @@ async def update_employee_info(session): async with client.start_session() as session: try: await run_transaction_with_retry(update_employee_info, session) - except Exception: + except Exception: # noqa: TRY203 # Do something with error. raise diff --git a/test/asynchronous/test_grid_file.py b/test/asynchronous/test_grid_file.py index 5319620624..9293725c83 100644 --- a/test/asynchronous/test_grid_file.py +++ b/test/asynchronous/test_grid_file.py @@ -23,7 +23,6 @@ import zipfile from io import BytesIO -from pymongo.asynchronous.database import AsyncDatabase from test.asynchronous import ( AsyncIntegrationTest, AsyncUnitTest, @@ -34,6 +33,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.objectid import ObjectId from gridfs.asynchronous.grid_file import ( _SEEK_CUR, @@ -51,6 +52,9 @@ from pymongo.message import _CursorAddress from test.utils_shared import OvertCommandListener +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False diff --git a/test/asynchronous/test_gridfs.py b/test/asynchronous/test_gridfs.py index 81aa1b6e8e..6b1c1c9460 100644 --- a/test/asynchronous/test_gridfs.py +++ b/test/asynchronous/test_gridfs.py @@ -29,11 +29,12 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + import gridfs from bson.binary import Binary from gridfs.asynchronous.grid_file import DEFAULT_CHUNK_SIZE, AsyncGridOutCursor from gridfs.errors import CorruptGridFile, FileExists, NoFile -from pymongo.asynchronous.database import AsyncDatabase from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.errors import ( ConfigurationError, @@ -45,6 +46,9 @@ from test.asynchronous.utils import async_joinall from test.utils_shared import one +if TYPE_CHECKING: + from pymongo.asynchronous.database import AsyncDatabase + _IS_SYNC = False diff --git a/test/asynchronous/test_heartbeat_monitoring.py b/test/asynchronous/test_heartbeat_monitoring.py index ff8c7c9eb9..9e13532f2d 100644 --- a/test/asynchronous/test_heartbeat_monitoring.py +++ b/test/asynchronous/test_heartbeat_monitoring.py @@ -61,7 +61,7 @@ async def _check_with_socket(self, *args, **kwargs): ) # zip gives us len(expected_results) pairs. - for expected, actual in zip(expected_results, listener.events): + for expected, actual in zip(expected_results, listener.events, strict=False): self.assertEqual(expected, actual.__class__.__name__) self.assertEqual(actual.connection_id, responses[0]) if expected != "ServerHeartbeatStartedEvent": diff --git a/test/asynchronous/test_index_management.py b/test/asynchronous/test_index_management.py index 3fe2be9534..4614cf7a21 100644 --- a/test/asynchronous/test_index_management.py +++ b/test/asynchronous/test_index_management.py @@ -21,8 +21,7 @@ import sys import time import uuid -from collections.abc import Mapping -from typing import Any +from typing import TYPE_CHECKING, Any import pytest @@ -38,6 +37,9 @@ from test.asynchronous.unified_format import generate_test_classes, get_test_path from test.utils_shared import AllowListEventListener, OvertCommandListener +if TYPE_CHECKING: + from collections.abc import Mapping + _IS_SYNC = False pytestmark = pytest.mark.search_index @@ -182,7 +184,6 @@ class TestSearchIndexProse(SearchIndexIntegrationBase): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_1(self): """Driver can successfully create and list search indexes.""" - # Create a new search index on ``self.coll0`` with the ``createSearchIndex`` helper. Use the following definition: model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = await self.coll0.create_search_index(model) @@ -202,7 +203,6 @@ async def test_case_1(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_2(self): """Driver can successfully create multiple indexes in batch.""" - # Create two new search indexes on ``self.coll0`` with the ``createSearchIndexes`` helper. name1 = "test-search-index-1" name2 = "test-search-index-2" @@ -237,7 +237,6 @@ async def test_case_2(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_3(self): """Driver can successfully drop search indexes.""" - # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = await self.coll0.create_search_index(model) @@ -256,7 +255,6 @@ async def test_case_3(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_4(self): """Driver can update a search index.""" - # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = await self.coll0.create_search_index(model) @@ -297,7 +295,6 @@ async def test_case_5(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_6(self): """Driver can successfully create and list search indexes with non-default readConcern and writeConcern.""" - # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``self.coll0``. coll0 = self.coll0.with_options( write_concern=WriteConcern(w="1"), read_concern=ReadConcern(level="majority") @@ -323,7 +320,6 @@ async def test_case_6(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) async def test_case_7(self): """Driver handles index types.""" - # Use these search and vector search definitions for indexes. search_definition = {"mappings": {"dynamic": False}} vector_search_definition = { diff --git a/test/asynchronous/test_json_util_integration.py b/test/asynchronous/test_json_util_integration.py index cbc307c0c0..b4c86f0bca 100644 --- a/test/asynchronous/test_json_util_integration.py +++ b/test/asynchronous/test_json_util_integration.py @@ -1,12 +1,14 @@ from __future__ import annotations -from collections.abc import MutableMapping -from typing import Any +from typing import TYPE_CHECKING, Any from bson import Binary, Code, DBRef, ObjectId, json_util from bson.binary import USER_DEFINED_SUBTYPE from test.asynchronous import AsyncIntegrationTest +if TYPE_CHECKING: + from collections.abc import MutableMapping + _IS_SYNC = False diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index 7866f1f7e6..cc669abcbe 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -181,7 +181,7 @@ async def lock_pool(self): # Wait for the unlock flag. unlock_pool = await self.wait(self.unlock, 10) if not unlock_pool: - raise Exception("timed out waiting for unlock signal: deadlock?") + raise TimeoutError("timed out waiting for unlock signal: deadlock?") async def wait(self, event: Event, timeout: int): if _IS_SYNC: @@ -189,7 +189,7 @@ async def wait(self, event: Event, timeout: int): else: try: await asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True diff --git a/test/asynchronous/test_locks.py b/test/asynchronous/test_locks.py index 4d207b509b..19166f309f 100644 --- a/test/asynchronous/test_locks.py +++ b/test/asynchronous/test_locks.py @@ -296,7 +296,7 @@ async def test_context_manager(self): async def test_timeout_in_block(self): condition = _async_create_condition(_async_create_lock()) async with condition: - with self.assertRaises(asyncio.TimeoutError): + with self.assertRaises(TimeoutError): await asyncio.wait_for(condition.wait(), timeout=0.5) async def test_cancelled_error_wakeup(self): diff --git a/test/asynchronous/test_monitor.py b/test/asynchronous/test_monitor.py index 62392fe689..9ad8f00ea3 100644 --- a/test/asynchronous/test_monitor.py +++ b/test/asynchronous/test_monitor.py @@ -110,7 +110,8 @@ async def test_cleanup_executors_on_client_close(self): @async_client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): """Test we silence noisy runtime errors fired when the AsyncMongoClient spawns a new thread - on process shutdown.""" + on process shutdown. + """ command = [ sys.executable, "-c", diff --git a/test/asynchronous/test_monitoring.py b/test/asynchronous/test_monitoring.py index e317f65ac3..fa2cb0189b 100644 --- a/test/asynchronous/test_monitoring.py +++ b/test/asynchronous/test_monitoring.py @@ -835,7 +835,7 @@ async def test_insert_many(self): count = 0 operation_id = started[0].operation_id self.assertIsInstance(operation_id, int) - for start, succeed in zip(started, succeeded): + for start, succeed in zip(started, succeeded, strict=True): self.assertIsInstance(start, monitoring.CommandStartedEvent) cmd = sanitize_cmd(start.command) self.assertEqual(["insert", "ordered", "documents"], list(cmd.keys())) @@ -875,7 +875,7 @@ async def test_insert_many_unacknowledged(self): documents = [] operation_id = started[0].operation_id self.assertIsInstance(operation_id, int) - for start, succeed in zip(started, succeeded): + for start, succeed in zip(started, succeeded, strict=True): self.assertIsInstance(start, monitoring.CommandStartedEvent) cmd = sanitize_cmd(start.command) cmd.pop("writeConcern", None) @@ -918,7 +918,7 @@ async def test_bulk_write(self): succeeded = self.listener.succeeded_events self.assertEqual(0, len(self.listener.failed_events)) operation_id = started[0].operation_id - pairs = list(zip(started, succeeded)) + pairs = list(zip(started, succeeded, strict=True)) self.assertEqual(3, len(pairs)) for start, succeed in pairs: self.assertIsInstance(start, monitoring.CommandStartedEvent) @@ -1034,7 +1034,7 @@ async def test_write_errors(self): succeeded = self.listener.succeeded_events self.assertEqual(0, len(self.listener.failed_events)) operation_id = started[0].operation_id - pairs = list(zip(started, succeeded)) + pairs = list(zip(started, succeeded, strict=True)) errors = [] for start, succeed in pairs: self.assertIsInstance(start, monitoring.CommandStartedEvent) diff --git a/test/asynchronous/test_periodic_executor.py b/test/asynchronous/test_periodic_executor.py index 42d64367ee..896dbba15c 100644 --- a/test/asynchronous/test_periodic_executor.py +++ b/test/asynchronous/test_periodic_executor.py @@ -23,7 +23,7 @@ import textwrap import threading import time -from typing import Any +from typing import Any, Optional from unittest import mock _interpreters: Any = None @@ -155,6 +155,92 @@ async def target(): await executor.join(timeout=2) self.assertGreaterEqual(called, 2) + async def test_close_from_own_task_does_not_cancel(self): + # Closing the executor from its own task must not cancel it + # (PYTHON-6226). + runs = 0 + + async def target(): + nonlocal runs + executor.close() + # Raises CancelledError here if close() cancelled this task. + await asyncio.sleep(0) + runs += 1 + return False + + executor = self._make_executor(target=target) + executor.open() + await executor.join(timeout=2) + self.assertEqual(runs, 1, "target did not finish after close() from its own task") + if not _IS_SYNC: + assert executor._task is not None + self.assertFalse(executor._task.cancelled(), "executor task cancelled itself") + # The executor can be restarted after a self-close. + executor.open() + await executor.join(timeout=2) + self.assertEqual(runs, 2, "executor did not restart after a self-close") + + async def test_close_from_thread_without_event_loop(self): + # close() can run off the event loop as a weakref callback, where + # asyncio.current_task() raises RuntimeError. + if _IS_SYNC: + started = threading.Event() + else: + started = asyncio.Event() + + async def target(): + started.set() + return True + + executor = self._make_executor(min_interval=0.5, target=target) + executor.open() + if _IS_SYNC: + started.wait(timeout=2) + else: + assert isinstance(started, asyncio.Event) + await asyncio.wait_for(started.wait(), timeout=2) + + close_error: BaseException | None = None + + def close_off_loop(): + nonlocal close_error + try: + executor.close() + except BaseException as exc: + close_error = exc + + real_task: Any = None + mock_task: Any = None + if not _IS_SYNC: + # Cancel a mock off the loop: cancelling the real task from + # another thread is not thread-safe under asyncio debug mode. + assert executor._task is not None + real_task = executor._task + mock_task = mock.MagicMock() + mock_task.cancelling.return_value = 0 + executor._task = mock_task + try: + thread = threading.Thread(target=close_off_loop) + thread.start() + if _IS_SYNC: + thread.join(timeout=2) + else: + # Do not block the event loop while joining the thread. + await asyncio.to_thread(thread.join, 2) + finally: + if not _IS_SYNC: + executor._task = real_task + self.assertIsNone(close_error, "close() raised from a thread without a running event loop") + if not _IS_SYNC: + assert mock_task is not None and real_task is not None + mock_task.cancel.assert_called_once() + # Cancel the real executor on the event loop thread. + real_task.cancel() + await executor.join(timeout=2) + self.assertTrue(executor._stopped) + if not _IS_SYNC: + self.assertTrue(real_task.cancelled()) + async def test_target_exception_stops_executor(self): call_count = 0 diff --git a/test/asynchronous/test_read_preferences.py b/test/asynchronous/test_read_preferences.py index 3728c3163c..5ff9de30f7 100644 --- a/test/asynchronous/test_read_preferences.py +++ b/test/asynchronous/test_read_preferences.py @@ -255,7 +255,7 @@ async def test_zero_latency(self): # Generate unique ping times. while len(ping_times) < len(self.client.nodes): ping_times.add(random.random()) - for ping_time, host in zip(ping_times, self.client.nodes): + for ping_time, host in zip(ping_times, self.client.nodes, strict=True): ServerDescription._host_to_round_trip_time[host] = ping_time try: client = await connected( @@ -578,7 +578,7 @@ def test_read_preference_hedge_deprecated(self): "secondaryPreferred": SecondaryPreferred, "nearest": Nearest, } - for _, cls in cases.items(): + for cls in cases.values(): with self.assertRaises(DeprecationWarning): cls(hedge={"enabled": True}) @@ -593,7 +593,7 @@ async def test_send_hedge(self): listener = OvertCommandListener() client = await self.async_rs_client(event_listeners=[listener]) await client.admin.command("ping") - for _mode, cls in cases.items(): + for cls in cases.values(): with _ignore_deprecations(): pref = cls(hedge={"enabled": True}) coll = client.test.get_collection("coll", read_preference=pref) diff --git a/test/asynchronous/test_retryable_writes.py b/test/asynchronous/test_retryable_writes.py index d40470bd8d..dc6d841aaf 100644 --- a/test/asynchronous/test_retryable_writes.py +++ b/test/asynchronous/test_retryable_writes.py @@ -367,6 +367,9 @@ async def test_batch_splitting_retry_fails(self): self.assertEqual(final_txn, expected_txn) self.assertEqual(await coll.find_one(projection={"_id": True}), {"_id": 1}) + # loadBalanced=true clients cannot use multiple seeds, and a retry routed to + # a different mongos is not observable through a load balancer (PYTHON-6262). + @async_client_context.require_no_load_balancer @async_client_context.require_multiple_mongoses @async_client_context.require_failCommand_fail_point async def test_retryable_writes_in_sharded_cluster_multiple_available(self): diff --git a/test/asynchronous/test_sdam_monitoring_spec.py b/test/asynchronous/test_sdam_monitoring_spec.py index 692625e326..9fc83bdff5 100644 --- a/test/asynchronous/test_sdam_monitoring_spec.py +++ b/test/asynchronous/test_sdam_monitoring_spec.py @@ -25,9 +25,10 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.json_util import object_hook from pymongo import AsyncMongoClient, monitoring -from pymongo.asynchronous.collection import AsyncCollection from pymongo.asynchronous.monitor import Monitor from pymongo.common import clean_node from pymongo.errors import ConnectionFailure, NotPrimaryError @@ -41,6 +42,9 @@ server_name_to_type, ) +if TYPE_CHECKING: + from pymongo.asynchronous.collection import AsyncCollection + _IS_SYNC = False # Location of JSON test specifications. @@ -67,7 +71,7 @@ def compare_topology_descriptions(expected, actual): if len(expected) != len(actual): return False for exp_server in expected: - for _address, actual_server in actual.items(): + for actual_server in actual.values(): if compare_server_descriptions(exp_server, actual_server): break else: diff --git a/test/asynchronous/test_server_selection.py b/test/asynchronous/test_server_selection.py index 4a15b7d93a..637a9b233e 100644 --- a/test/asynchronous/test_server_selection.py +++ b/test/asynchronous/test_server_selection.py @@ -118,7 +118,7 @@ async def all_hosts_started(): async def test_invalid_server_selector(self): # Client initialization must fail if server_selector is not callable. for selector_candidate in [[], 10, "string", {}]: - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): AsyncMongoClient(connect=False, server_selector=selector_candidate) # None value for server_selector is OK. diff --git a/test/asynchronous/test_session.py b/test/asynchronous/test_session.py index 6e3a31d2a7..c6e3d58db8 100644 --- a/test/asynchronous/test_session.py +++ b/test/asynchronous/test_session.py @@ -19,10 +19,9 @@ import copy import sys import time -from collections.abc import Callable from inspect import iscoroutinefunction from io import BytesIO -from typing import Any +from typing import TYPE_CHECKING, Any from test.asynchronous.helpers import ExceptionCatchingTask @@ -53,6 +52,9 @@ async_wait_until, ) +if TYPE_CHECKING: + from collections.abc import Callable + _IS_SYNC = False @@ -1019,7 +1021,7 @@ async def test_core(self): self.assertIsNone(sess2.cluster_time) self.assertIsNone(sess2.operation_time) self.assertRaises(TypeError, sess2.advance_cluster_time, 1) - self.assertRaises(ValueError, sess2.advance_cluster_time, {}) + self.assertRaises(TypeError, sess2.advance_cluster_time, {}) self.assertRaises(TypeError, sess2.advance_operation_time, 1) # No error assert sess.cluster_time is not None diff --git a/test/asynchronous/test_sfp.py b/test/asynchronous/test_sfp.py index d9b6350002..c3d00a283c 100644 --- a/test/asynchronous/test_sfp.py +++ b/test/asynchronous/test_sfp.py @@ -19,17 +19,19 @@ import os import sys import unittest -from typing import Any +from typing import TYPE_CHECKING, Any import pytest sys.path[0:0] = [""] from bson import ObjectId -from pymongo.asynchronous.mongo_client import AsyncMongoClient from pymongo.server_api import ServerApi from test.asynchronous import AsyncPyMongoTestCase +if TYPE_CHECKING: + from pymongo.asynchronous.mongo_client import AsyncMongoClient + _IS_SYNC = False pytestmark = pytest.mark.sfp @@ -46,7 +48,7 @@ def _require_env(name: str) -> str: value = os.environ.get(name) if not value: - raise Exception(f"Must set {name} env variable to test.") + raise ValueError(f"Must set {name} env variable to test.") return value diff --git a/test/asynchronous/test_ssl.py b/test/asynchronous/test_ssl.py index 271f5e37fe..a27308a64a 100644 --- a/test/asynchronous/test_ssl.py +++ b/test/asynchronous/test_ssl.py @@ -148,7 +148,6 @@ def test_ssl_session_cache(self): @unittest.skipUnless(_IS_SYNC, "Tests sync wrap_socket path only") def test_tls_session_reused_on_second_connection(self): """Cached TLS session is passed to wrap_socket on subsequent connections.""" - fake_session = object() cache: list = [fake_session] diff --git a/test/asynchronous/unified_format.py b/test/asynchronous/unified_format.py index 31aca76cab..edcc43ad3c 100644 --- a/test/asynchronous/unified_format.py +++ b/test/asynchronous/unified_format.py @@ -31,17 +31,15 @@ import time import traceback from collections import defaultdict -from collections.abc import Mapping from inspect import iscoroutinefunction from pathlib import Path -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Optional import pytest import pymongo from bson import SON, json_util from bson.codec_options import DEFAULT_CODEC_OPTIONS -from bson.objectid import ObjectId from gridfs import AsyncGridFSBucket, GridOut, NoFile from gridfs.errors import CorruptGridFile from pymongo import ASCENDING, AsyncMongoClient, CursorType, _csot @@ -79,7 +77,6 @@ from pymongo.server_selectors import Selection, writable_server_selector from pymongo.server_type import SERVER_TYPE from pymongo.topology_description import TopologyDescription -from pymongo.typings import _Address from pymongo.write_concern import WriteConcern from test.asynchronous import ( AsyncIntegrationTest, @@ -113,6 +110,12 @@ ) from test.version import Version +if TYPE_CHECKING: + from collections.abc import Mapping + + from bson.objectid import ObjectId + from pymongo.typings import _Address + _IS_SYNC = False IS_INTERRUPTED = False @@ -748,7 +751,9 @@ def process_error(self, exception, spec): ) actual_write_concern_errors = exception.details.get("writeConcernErrors", []) self.assertEqual(len(write_concern_errors), len(actual_write_concern_errors)) - for expected_wce, actual_wce in zip(write_concern_errors, actual_write_concern_errors): + for expected_wce, actual_wce in zip( + write_concern_errors, actual_write_concern_errors, strict=True + ): # Use the spec's WriteConcernError field names. formatted_actual_wce = { "code": actual_wce.get("code", ""), @@ -1171,10 +1176,9 @@ def _testOperation_assertSessionUnpinned(self, spec): self.assertIsNone(session._transaction.pinned_address) def __get_last_two_command_lsids(self, listener): - cmd_started_events = [] - for event in reversed(listener.events): - if isinstance(event, CommandStartedEvent): - cmd_started_events.append(event) + cmd_started_events = [ + event for event in reversed(listener.events) if isinstance(event, CommandStartedEvent) + ] if len(cmd_started_events) < 2: self.fail( "Needed 2 CommandStartedEvents to compare lsids, got %s" % (len(cmd_started_events)) @@ -1280,7 +1284,7 @@ async def _testOperation_waitForPrimaryChange(self, spec: dict) -> None: old_description: TopologyDescription = self.entity_map[spec["priorTopologyDescription"]] timeout = spec["timeoutMS"] / 1000.0 - def get_primary(td: TopologyDescription) -> Optional[_Address]: + def get_primary(td: TopologyDescription) -> _Address | None: servers = writable_server_selector(Selection.from_topology_description(td)) if servers and servers[0].server_type == SERVER_TYPE.RSPrimary: return servers[0].address @@ -1466,7 +1470,7 @@ def format_logs(log_list): len(actual_logs), f"expected {client['messages']} but got {actual_logs}", ) - for expected_msg, actual_msg in zip(client["messages"], actual_logs): + for expected_msg, actual_msg in zip(client["messages"], actual_logs, strict=True): expected_data, actual_data = expected_msg.pop("data"), actual_msg.pop("data") if "failureIsRedacted" in expected_msg: diff --git a/test/asynchronous/utils.py b/test/asynchronous/utils.py index 3e6669a753..ebdf70c038 100644 --- a/test/asynchronous/utils.py +++ b/test/asynchronous/utils.py @@ -27,10 +27,9 @@ import unittest from functools import wraps from inspect import iscoroutinefunction +from typing import TYPE_CHECKING from bson.son import SON -from pymongo import AsyncMongoClient -from pymongo.asynchronous.pool import Pool from pymongo.errors import ConfigurationError from pymongo.hello import HelloCompat from pymongo.lock import _async_create_lock @@ -39,6 +38,10 @@ from pymongo.read_preferences import ReadPreference from pymongo.server_selectors import any_server_selector, writable_server_selector +if TYPE_CHECKING: + from pymongo import AsyncMongoClient + from pymongo.asynchronous.pool import Pool + _IS_SYNC = False @@ -215,9 +218,9 @@ async def wrapper(*args, **kwargs): passes += 1 if passes == min_passes: return result - except Exception as e: + except Exception: if i == max_runs - 1: - raise e + raise print( f"Retrying after attempt {i + 1} of {func_name or target_func.__name__} failed with ({reason})):\n" f"{traceback.format_exc()}", diff --git a/test/atlas/test_connection.py b/test/atlas/test_connection.py index 7424db83e6..3b018264f3 100644 --- a/test/atlas/test_connection.py +++ b/test/atlas/test_connection.py @@ -51,7 +51,7 @@ class TestAtlasConnect(PyMongoTestCase): def connect(self, uri): if not uri: - raise Exception("Must set env variable to test.") + raise ValueError("Must set env variable to test.") client = self.simple_client(uri) # No TLS error client.admin.command("ping") diff --git a/test/client-side-encryption/etc/data/encryptedFields-prefix-suffix-preview.json b/test/client-side-encryption/etc/data/encryptedFields-prefix-suffix-preview.json deleted file mode 100644 index 047064beb1..0000000000 --- a/test/client-side-encryption/etc/data/encryptedFields-prefix-suffix-preview.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "fields": [ - { - "keyId": { - "$binary": { - "base64": "EjRWeBI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "path": "encryptedText", - "bsonType": "string", - "queries": [ - { - "queryType": "prefixPreview", - "strMinQueryLength": { - "$numberInt": "2" - }, - "strMaxQueryLength": { - "$numberInt": "10" - }, - "contention": { - "$numberLong": "0" - }, - "caseSensitive": true, - "diacriticSensitive": true - }, - { - "queryType": "suffixPreview", - "strMinQueryLength": { - "$numberInt": "2" - }, - "strMaxQueryLength": { - "$numberInt": "10" - }, - "contention": { - "$numberLong": "0" - }, - "caseSensitive": true, - "diacriticSensitive": true - } - ] - } - ] -} diff --git a/test/client-side-encryption/etc/data/encryptedFields-substring-preview.json b/test/client-side-encryption/etc/data/encryptedFields-substring-preview.json deleted file mode 100644 index a519edc627..0000000000 --- a/test/client-side-encryption/etc/data/encryptedFields-substring-preview.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "fields": [ - { - "keyId": { - "$binary": { - "base64": "EjRWeBI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "path": "encryptedText", - "bsonType": "string", - "queries": [ - { - "queryType": "substringPreview", - "strMaxLength": { - "$numberInt": "10" - }, - "strMinQueryLength": { - "$numberInt": "2" - }, - "strMaxQueryLength": { - "$numberInt": "6" - }, - "contention": { - "$numberLong": "0" - }, - "caseSensitive": true, - "diacriticSensitive": true - } - ] - } - ] -} diff --git a/test/client-side-encryption/spec/unified/QE-Text-prefixPreview.json b/test/client-side-encryption/spec/unified/QE-Text-prefixPreview.json deleted file mode 100644 index 51e72fd3ca..0000000000 --- a/test/client-side-encryption/spec/unified/QE-Text-prefixPreview.json +++ /dev/null @@ -1,339 +0,0 @@ -{ - "description": "QE-Text-prefixPreview", - "schemaVersion": "1.25", - "runOnRequirements": [ - { - "minServerVersion": "8.2.0", - "maxServerVersion": "8.99.99", - "topologies": [ - "replicaset", - "sharded", - "load-balanced" - ], - "csfle": { - "minLibmongocryptVersion": "1.19.1" - } - } - ], - "createEntities": [ - { - "client": { - "id": "client", - "autoEncryptOpts": { - "keyVaultNamespace": "keyvault.datakeys", - "kmsProviders": { - "local": { - "key": "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk" - } - } - }, - "observeEvents": [ - "commandStartedEvent" - ] - } - }, - { - "database": { - "id": "db", - "client": "client", - "databaseName": "db" - } - }, - { - "collection": { - "id": "coll", - "database": "db", - "collectionName": "coll" - } - } - ], - "initialData": [ - { - "databaseName": "keyvault", - "collectionName": "datakeys", - "documents": [ - { - "_id": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "keyMaterial": { - "$binary": { - "base64": "HBk9BWihXExNDvTp1lUxOuxuZK2Pe2ZdVdlsxPEBkiO1bS4mG5NNDsQ7zVxJAH8BtdOYp72Ku4Y3nwc0BUpIKsvAKX4eYXtlhv5zUQxWdeNFhg9qK7qb8nqhnnLeT0f25jFSqzWJoT379hfwDeu0bebJHr35QrJ8myZdPMTEDYF08QYQ48ShRBli0S+QzBHHAQiM2iJNr4svg2WR8JSeWQ==", - "subType": "00" - } - }, - "creationDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "updateDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "status": { - "$numberInt": "0" - }, - "masterKey": { - "provider": "local" - } - } - ] - }, - { - "databaseName": "db", - "collectionName": "coll", - "documents": [], - "createOptions": { - "encryptedFields": { - "fields": [ - { - "keyId": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "path": "encryptedText", - "bsonType": "string", - "queries": [ - { - "queryType": "prefixPreview", - "contention": { - "$numberLong": "0" - }, - "strMinQueryLength": { - "$numberLong": "3" - }, - "strMaxQueryLength": { - "$numberLong": "30" - }, - "caseSensitive": true, - "diacriticSensitive": true - } - ] - } - ] - } - } - } - ], - "tests": [ - { - "description": "Insert QE prefixPreview", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - } - ], - "expectEvents": [ - { - "client": "client", - "events": [ - { - "commandStartedEvent": { - "command": { - "listCollections": 1, - "filter": { - "name": "coll" - } - }, - "commandName": "listCollections" - } - }, - { - "commandStartedEvent": { - "command": { - "find": "datakeys", - "filter": { - "$or": [ - { - "_id": { - "$in": [ - { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - } - ] - } - }, - { - "keyAltNames": { - "$in": [] - } - } - ] - }, - "$db": "keyvault", - "readConcern": { - "level": "majority" - } - }, - "commandName": "find" - } - }, - { - "commandStartedEvent": { - "command": { - "insert": "coll", - "documents": [ - { - "_id": 1, - "encryptedText": { - "$$type": "binData" - } - } - ], - "ordered": true - }, - "commandName": "insert" - } - } - ] - } - ] - }, - { - "description": "Query with matching $encStrStartsWith", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrStartsWith": { - "input": "$encryptedText", - "prefix": "foo" - } - } - } - }, - "object": "coll", - "expectResult": [ - { - "_id": { - "$numberInt": "1" - }, - "encryptedText": "foobar", - "__safeContent__": [ - { - "$binary": { - "base64": "wpaMBVDjL4bHf9EtSP52PJFzyNn1R19+iNI/hWtvzdk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "fmUMXTMV/XRiN0IL3VXxSEn6SQG9E6Po30kJKB8JJlQ=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "vZIDMiFDgjmLNYVrrbnq1zT4hg7sGpe/PMtighSsnRc=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "26Z5G+sHTzV3D7F8Y0m08389USZ2afinyFV3ez9UEBQ=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "q/JEq8of7bE0QE5Id0XuOsNQ4qVpANYymcPQDUL2Ywk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "Uvvv46LkfbgLoPqZ6xTBzpgoYRTM6FUgRdqZ9eaVojI=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "nMxdq2lladuBJA3lv3JC2MumIUtRJBNJVLp3PVE6nQk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "hS3V0qq5CF/SkTl3ZWWWgXcAJ8G5yGtkY2RwcHNc5Oc=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "McgwYUxfKj5+4D0vskZymy4KA82s71MR25iV/Enutww=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "Ciqdk1b+t+Vrr6oIlFFk0Zdym5BPmwN3glQ0/VcsVdM=", - "subType": "00" - } - } - ] - } - ] - } - ] - }, - { - "description": "Query with non-matching $encStrStartsWith", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrStartsWith": { - "input": "$encryptedText", - "prefix": "bar" - } - } - } - }, - "object": "coll", - "expectResult": [] - } - ] - } - ] -} diff --git a/test/client-side-encryption/spec/unified/QE-Text-substringPreview.json b/test/client-side-encryption/spec/unified/QE-Text-substringPreview.json deleted file mode 100644 index 1df3170958..0000000000 --- a/test/client-side-encryption/spec/unified/QE-Text-substringPreview.json +++ /dev/null @@ -1,468 +0,0 @@ -{ - "description": "QE-Text-substringPreview", - "schemaVersion": "1.25", - "runOnRequirements": [ - { - "minServerVersion": "8.2.0", - "maxServerVersion": "8.99.99", - "topologies": [ - "replicaset", - "sharded", - "load-balanced" - ], - "csfle": { - "minLibmongocryptVersion": "1.15.0" - } - } - ], - "createEntities": [ - { - "client": { - "id": "client", - "autoEncryptOpts": { - "keyVaultNamespace": "keyvault.datakeys", - "kmsProviders": { - "local": { - "key": "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk" - } - } - }, - "observeEvents": [ - "commandStartedEvent" - ] - } - }, - { - "database": { - "id": "db", - "client": "client", - "databaseName": "db" - } - }, - { - "collection": { - "id": "coll", - "database": "db", - "collectionName": "coll" - } - } - ], - "initialData": [ - { - "databaseName": "keyvault", - "collectionName": "datakeys", - "documents": [ - { - "_id": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "keyMaterial": { - "$binary": { - "base64": "HBk9BWihXExNDvTp1lUxOuxuZK2Pe2ZdVdlsxPEBkiO1bS4mG5NNDsQ7zVxJAH8BtdOYp72Ku4Y3nwc0BUpIKsvAKX4eYXtlhv5zUQxWdeNFhg9qK7qb8nqhnnLeT0f25jFSqzWJoT379hfwDeu0bebJHr35QrJ8myZdPMTEDYF08QYQ48ShRBli0S+QzBHHAQiM2iJNr4svg2WR8JSeWQ==", - "subType": "00" - } - }, - "creationDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "updateDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "status": { - "$numberInt": "0" - }, - "masterKey": { - "provider": "local" - } - } - ] - }, - { - "databaseName": "db", - "collectionName": "coll", - "documents": [], - "createOptions": { - "encryptedFields": { - "fields": [ - { - "keyId": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "path": "encryptedText", - "bsonType": "string", - "queries": [ - { - "queryType": "substringPreview", - "contention": { - "$numberLong": "0" - }, - "strMinQueryLength": { - "$numberLong": "3" - }, - "strMaxQueryLength": { - "$numberLong": "6" - }, - "strMaxLength": { - "$numberLong": "20" - }, - "caseSensitive": true, - "diacriticSensitive": true - } - ] - } - ] - } - } - } - ], - "tests": [ - { - "description": "Insert QE substringPreview", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - } - ], - "expectEvents": [ - { - "client": "client", - "events": [ - { - "commandStartedEvent": { - "command": { - "listCollections": 1, - "filter": { - "name": "coll" - } - }, - "commandName": "listCollections" - } - }, - { - "commandStartedEvent": { - "command": { - "find": "datakeys", - "filter": { - "$or": [ - { - "_id": { - "$in": [ - { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - } - ] - } - }, - { - "keyAltNames": { - "$in": [] - } - } - ] - }, - "$db": "keyvault", - "readConcern": { - "level": "majority" - } - }, - "commandName": "find" - } - }, - { - "commandStartedEvent": { - "command": { - "insert": "coll", - "documents": [ - { - "_id": 1, - "encryptedText": { - "$$type": "binData" - } - } - ], - "ordered": true - }, - "commandName": "insert" - } - } - ] - } - ] - }, - { - "description": "Query with matching $encStrContains", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrContains": { - "input": "$encryptedText", - "substring": "oba" - } - } - } - }, - "object": "coll", - "expectResult": [ - { - "_id": { - "$numberInt": "1" - }, - "encryptedText": "foobar", - "__safeContent__": [ - { - "$binary": { - "base64": "wpaMBVDjL4bHf9EtSP52PJFzyNn1R19+iNI/hWtvzdk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "IpY3x/jjm8j/74jAdUhgxdM5hk68zR0zv/lTKm/72Vg=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "G+ky260C6QiOfIxKz14FmaMbAxvui1BKJO/TnLOHlGk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "7dv3gAKe9vwJMZmpB40pRCwRTmc7ds9UkGhxH8j084E=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "o0V+Efn6x8XQdE80F1tztNaT3qxHjcsd9DOQ47BtmQk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "sJvrCjyVot7PIZFsdRehWFANKAj6fmBaj3FLbz/dZLE=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "e98auxFmu02h5MfBIARk29MI7hSmvN3F9DaQ0xjqoEM=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "US83krGNov/ezL6IhsY5eEOCxv1xUPDIEL/nmY0IKi0=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "P2Aq5+OHZPG0CWIdmZvWq9c/18ZKVYW3vbxd+WU/TXU=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "8AdPRPnSzcd5uhq4TZfNvNeF0XjLNVwAsJJMTtktw84=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "9O6u/G51I4ZHFLhL4ZLuudbr0s202A2QnPfThmOXPhI=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "N7AjYVyVlv6+lVSTM+cIxRL3SMgs3G5LgxSs+jrgDkI=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "RbGF7dQbPGYQFd9DDO1hPz1UlLOJ77FAC6NsjGwJeos=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "m7srHMgKm6kZwsNx8rc45pmw0/9Qro6xuQ8lZS3+RYk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "K75CNU3JyKFqZWPiIsVi4+n7DhYmcPl/nEhQ3d88mVI=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "c7bwGpUZc/7JzEnMS7qQ/TPuXZyrmMihFaAV6zIqbZc=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "rDvEdUgEk8u4Srt3ETokWs2FXcnyJaRGQ+NbkFwi2rQ=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "VcdZj9zfveRBRlpCR2OYWau2+GokOFb73TE3gpElNiU=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "eOa9o2xfA6OgkbYUxd6wQJicaeN6guhy2V66W3ALsaA=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "1xGkJh+um70XiRd8lKLDtyHgDqrf7/59Mg7X0+KZh8k=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "OSvllqHxycbcZN4phR6NDujY3ttA59o7nQJ6V9eJpX0=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "ZTX1pyk8Vdw0BSbJx7GeJNcQf3tGKxbrrNSTqBqUWkg=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "cn7V05zb5iXwYrePGMHztC+GRq+Tj8IMpRDraauPhSE=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "E9bV9KyrZxHJSUmMg0HrDK4gGN+75ruelAnrM6hXQgY=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "WrssTNmdgXoTGpbaF0JLRCGH6cDQuz1XEFNTy98nrb0=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "jZmyOJP35dsxQ/OY5U4ISpVRIYr8iedNfcwZiKt29Qc=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "d2mocORMbX9MX+/itAW8r1kxVw2/uii4vzXtc+2CIRQ=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "JBnJy58eRPhDo3DuZvsHbvQDiHXxdtAx1Eif66k5SfA=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "OjbDulC8s62v0pgweBSsQqtJjJBwH5JinfJpj7nVr+A=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "85i7KT2GP9nSda3Gsil5LKubhq0LDtc22pxBxHpR+nE=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "u9Fvsclwrs9lwIcMPV/fMZD7L3d5anSfJQVjQb9mgLg=", - "subType": "00" - } - } - ] - } - ] - } - ] - }, - { - "description": "Query with non-matching $encStrContains", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrContains": { - "input": "$encryptedText", - "substring": "blah" - } - } - } - }, - "object": "coll", - "expectResult": [] - } - ] - } - ] -} diff --git a/test/client-side-encryption/spec/unified/QE-Text-suffixPreview.json b/test/client-side-encryption/spec/unified/QE-Text-suffixPreview.json deleted file mode 100644 index e30d0cfd58..0000000000 --- a/test/client-side-encryption/spec/unified/QE-Text-suffixPreview.json +++ /dev/null @@ -1,339 +0,0 @@ -{ - "description": "QE-Text-suffixPreview", - "schemaVersion": "1.25", - "runOnRequirements": [ - { - "minServerVersion": "8.2.0", - "maxServerVersion": "8.99.99", - "topologies": [ - "replicaset", - "sharded", - "load-balanced" - ], - "csfle": { - "minLibmongocryptVersion": "1.19.1" - } - } - ], - "createEntities": [ - { - "client": { - "id": "client", - "autoEncryptOpts": { - "keyVaultNamespace": "keyvault.datakeys", - "kmsProviders": { - "local": { - "key": "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk" - } - } - }, - "observeEvents": [ - "commandStartedEvent" - ] - } - }, - { - "database": { - "id": "db", - "client": "client", - "databaseName": "db" - } - }, - { - "collection": { - "id": "coll", - "database": "db", - "collectionName": "coll" - } - } - ], - "initialData": [ - { - "databaseName": "keyvault", - "collectionName": "datakeys", - "documents": [ - { - "_id": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "keyMaterial": { - "$binary": { - "base64": "HBk9BWihXExNDvTp1lUxOuxuZK2Pe2ZdVdlsxPEBkiO1bS4mG5NNDsQ7zVxJAH8BtdOYp72Ku4Y3nwc0BUpIKsvAKX4eYXtlhv5zUQxWdeNFhg9qK7qb8nqhnnLeT0f25jFSqzWJoT379hfwDeu0bebJHr35QrJ8myZdPMTEDYF08QYQ48ShRBli0S+QzBHHAQiM2iJNr4svg2WR8JSeWQ==", - "subType": "00" - } - }, - "creationDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "updateDate": { - "$date": { - "$numberLong": "1648914851981" - } - }, - "status": { - "$numberInt": "0" - }, - "masterKey": { - "provider": "local" - } - } - ] - }, - { - "databaseName": "db", - "collectionName": "coll", - "documents": [], - "createOptions": { - "encryptedFields": { - "fields": [ - { - "keyId": { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - }, - "path": "encryptedText", - "bsonType": "string", - "queries": [ - { - "queryType": "suffixPreview", - "contention": { - "$numberLong": "0" - }, - "strMinQueryLength": { - "$numberLong": "3" - }, - "strMaxQueryLength": { - "$numberLong": "30" - }, - "caseSensitive": true, - "diacriticSensitive": true - } - ] - } - ] - } - } - } - ], - "tests": [ - { - "description": "Insert QE suffixPreview", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - } - ], - "expectEvents": [ - { - "client": "client", - "events": [ - { - "commandStartedEvent": { - "command": { - "listCollections": 1, - "filter": { - "name": "coll" - } - }, - "commandName": "listCollections" - } - }, - { - "commandStartedEvent": { - "command": { - "find": "datakeys", - "filter": { - "$or": [ - { - "_id": { - "$in": [ - { - "$binary": { - "base64": "q83vqxI0mHYSNBI0VniQEg==", - "subType": "04" - } - } - ] - } - }, - { - "keyAltNames": { - "$in": [] - } - } - ] - }, - "$db": "keyvault", - "readConcern": { - "level": "majority" - } - }, - "commandName": "find" - } - }, - { - "commandStartedEvent": { - "command": { - "insert": "coll", - "documents": [ - { - "_id": 1, - "encryptedText": { - "$$type": "binData" - } - } - ], - "ordered": true - }, - "commandName": "insert" - } - } - ] - } - ] - }, - { - "description": "Query with matching $encStrEndsWith", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrEndsWith": { - "input": "$encryptedText", - "suffix": "bar" - } - } - } - }, - "object": "coll", - "expectResult": [ - { - "_id": { - "$numberInt": "1" - }, - "encryptedText": "foobar", - "__safeContent__": [ - { - "$binary": { - "base64": "wpaMBVDjL4bHf9EtSP52PJFzyNn1R19+iNI/hWtvzdk=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "uDCWsucUsJemUP7pmeb+Kd8B9qupVzI8wnLFqX1rkiU=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "W3E1x4bHZ8SEHFz4zwXM0G5Z5WSwBhnxE8x5/qdP6JM=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "6g/TXVDDf6z+ntResIvTKWdmIy4ajQ1rhwdNZIiEG7A=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "hU+u/T3D6dHDpT3d/v5AlgtRoAufCXCAyO2jQlgsnCw=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "vrPnq0AtBIURNgNGA6HJL+5/p5SBWe+qz8505TRo/dE=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "W5pylBxdv2soY2NcBfPiHDVLTS6tx+0ULkI8gysBeFY=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "oWO3xX3x0bYUJGK2S1aPAmlU3Xtfsgb9lTZ6flGAlsg=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "SjZGucTEUbdpd86O8yj1pyMyBOOKxvAQ9C8ngZ9C5UE=", - "subType": "00" - } - }, - { - "$binary": { - "base64": "CEaMZkxVDVbnXr+To0DOyvsva04UQkIYP3KtgYVVwf8=", - "subType": "00" - } - } - ] - } - ] - } - ] - }, - { - "description": "Query with non-matching $encStrEndsWith", - "operations": [ - { - "name": "insertOne", - "arguments": { - "document": { - "_id": 1, - "encryptedText": "foobar" - } - }, - "object": "coll" - }, - { - "name": "find", - "arguments": { - "filter": { - "$expr": { - "$encStrEndsWith": { - "input": "$encryptedText", - "suffix": "foo" - } - } - } - }, - "object": "coll", - "expectResult": [] - } - ] - } - ] -} diff --git a/test/connection_logging/connection-pool-options.json b/test/connection_logging/connection-pool-options.json index 7055a54869..b7e6474e61 100644 --- a/test/connection_logging/connection-pool-options.json +++ b/test/connection_logging/connection-pool-options.json @@ -297,162 +297,6 @@ ] } ] - }, - { - "description": "waitQueueSize should be included in connection pool created message when specified", - "operations": [ - { - "name": "createEntities", - "object": "testRunner", - "arguments": { - "entities": [ - { - "client": { - "id": "client", - "observeEvents": [ - "poolReadyEvent" - ], - "observeLogMessages": { - "connection": "debug" - }, - "uriOptions": { - "waitQueueSize": 100 - } - } - } - ] - } - }, - { - "name": "waitForEvent", - "object": "testRunner", - "arguments": { - "client": "client", - "event": { - "poolReadyEvent": {} - }, - "count": 1 - } - } - ], - "expectLogMessages": [ - { - "client": "client", - "messages": [ - { - "level": "debug", - "component": "connection", - "data": { - "message": "Connection pool created", - "serverHost": { - "$$type": "string" - }, - "serverPort": { - "$$type": [ - "int", - "long" - ] - }, - "waitQueueSize": 100 - } - }, - { - "level": "debug", - "component": "connection", - "data": { - "message": "Connection pool ready", - "serverHost": { - "$$type": "string" - }, - "serverPort": { - "$$type": [ - "int", - "long" - ] - } - } - } - ] - } - ] - }, - { - "description": "waitQueueMultiple should be included in connection pool created message when specified", - "operations": [ - { - "name": "createEntities", - "object": "testRunner", - "arguments": { - "entities": [ - { - "client": { - "id": "client", - "observeEvents": [ - "poolReadyEvent" - ], - "observeLogMessages": { - "connection": "debug" - }, - "uriOptions": { - "waitQueueSize": 5 - } - } - } - ] - } - }, - { - "name": "waitForEvent", - "object": "testRunner", - "arguments": { - "client": "client", - "event": { - "poolReadyEvent": {} - }, - "count": 1 - } - } - ], - "expectLogMessages": [ - { - "client": "client", - "messages": [ - { - "level": "debug", - "component": "connection", - "data": { - "message": "Connection pool created", - "serverHost": { - "$$type": "string" - }, - "serverPort": { - "$$type": [ - "int", - "long" - ] - }, - "waitQueueMultiple": 5 - } - }, - { - "level": "debug", - "component": "connection", - "data": { - "message": "Connection pool ready", - "serverHost": { - "$$type": "string" - }, - "serverPort": { - "$$type": [ - "int", - "long" - ] - } - } - } - ] - } - ] } ] } diff --git a/test/helpers.py b/test/helpers.py index 6814326d38..e183b12fe3 100644 --- a/test/helpers.py +++ b/test/helpers.py @@ -113,7 +113,7 @@ def __del__(self): f"EVENTS_QUEUE_FREQUENCY={common.EVENTS_QUEUE_FREQUENCY}, stack:\n{self._stack}" ) self.disable() - raise Exception(msg) + raise RuntimeError(msg) # Global knobs to speed up the test suite. @@ -141,7 +141,7 @@ def __init__(self, **kwargs): def start(self): self.task = asyncio.create_task(self.run(), name=self.name) - def join(self, timeout: Optional[float] = None): # type: ignore[override] + def join(self, timeout: float | None = None): # type: ignore[override] if self.task is not None: asyncio.wait([self.task], timeout=timeout) diff --git a/test/mockupdb/test_cursor_namespace.py b/test/mockupdb/test_cursor_namespace.py index 7cf0048bd9..8d7dfb8c9b 100644 --- a/test/mockupdb/test_cursor_namespace.py +++ b/test/mockupdb/test_cursor_namespace.py @@ -30,9 +30,13 @@ _HAVE_MOCKUPDB = False -from pymongo import MongoClient +from typing import TYPE_CHECKING + from pymongo.common import MIN_SUPPORTED_WIRE_VERSION +if TYPE_CHECKING: + from pymongo import MongoClient + pytestmark = pytest.mark.mockupdb diff --git a/test/performance/async_perf_test.py b/test/performance/async_perf_test.py index e4a68e228e..ea10b6f56b 100644 --- a/test/performance/async_perf_test.py +++ b/test/performance/async_perf_test.py @@ -43,10 +43,9 @@ import asyncio import os import sys -import tempfile import time import warnings -from typing import Any, Optional, Union +from typing import Any import pytest @@ -397,7 +396,7 @@ async def do_task(self): class TestSmallDocBulkMixedOps(SmallDocMixedTest, AsyncPyMongoTestCase): async def asyncSetUp(self): await super().asyncSetUp() - self.models: list[Union[InsertOne, ReplaceOne, DeleteOne]] = [] + self.models: list[InsertOne | ReplaceOne | DeleteOne] = [] for doc in self.documents: self.models.append(InsertOne(document=doc)) self.models.append(ReplaceOne(filter={}, replacement=doc.copy(), upsert=True)) @@ -411,7 +410,7 @@ class TestSmallDocClientBulkMixedOps(SmallDocMixedTest, AsyncPyMongoTestCase): @async_client_context.require_version_min(8, 0, 0, -24) async def asyncSetUp(self): await super().asyncSetUp() - self.models: list[Union[InsertOne, ReplaceOne, DeleteOne]] = [] + self.models: list[InsertOne | ReplaceOne | DeleteOne] = [] for doc in self.documents: self.models.append(InsertOne(namespace="perftest.corpus", document=doc)) self.models.append( diff --git a/test/performance/perf_test.py b/test/performance/perf_test.py index 5ec13a2b56..0b8be88591 100644 --- a/test/performance/perf_test.py +++ b/test/performance/perf_test.py @@ -47,7 +47,7 @@ import threading import time import warnings -from typing import Any, Optional, Union +from typing import Any import pytest @@ -478,7 +478,7 @@ def do_task(self): class TestSmallDocBulkMixedOps(SmallDocMixedTest, unittest.TestCase): def setUp(self): super().setUp() - self.models: list[Union[InsertOne, ReplaceOne, DeleteOne]] = [] + self.models: list[InsertOne | ReplaceOne | DeleteOne] = [] for doc in self.documents: self.models.append(InsertOne(document=doc)) self.models.append(ReplaceOne(filter={}, replacement=doc.copy(), upsert=True)) @@ -492,7 +492,7 @@ class TestSmallDocClientBulkMixedOps(SmallDocMixedTest, unittest.TestCase): @client_context.require_version_min(8, 0, 0, -24) def setUp(self): super().setUp() - self.models: list[Union[InsertOne, ReplaceOne, DeleteOne]] = [] + self.models: list[InsertOne | ReplaceOne | DeleteOne] = [] for doc in self.documents: self.models.append(InsertOne(namespace="perftest.corpus", document=doc)) self.models.append( @@ -573,7 +573,7 @@ def do_task(self): self.bucket.open_download_stream(self.uploaded_id).read() -proc_client: Optional[MongoClient] = None +proc_client: MongoClient | None = None def proc_init(client_kwargs): diff --git a/test/read_write_concern/write-concern-errors/aggregate.json b/test/read_write_concern/write-concern-errors/aggregate.json index e4b33ae33c..b55beb932e 100644 --- a/test/read_write_concern/write-concern-errors/aggregate.json +++ b/test/read_write_concern/write-concern-errors/aggregate.json @@ -50,7 +50,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -98,7 +99,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/bulkWrite.json b/test/read_write_concern/write-concern-errors/bulkWrite.json index a357c77c55..2aabb4bfb0 100644 --- a/test/read_write_concern/write-concern-errors/bulkWrite.json +++ b/test/read_write_concern/write-concern-errors/bulkWrite.json @@ -43,7 +43,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/client-bulkWrite.json b/test/read_write_concern/write-concern-errors/client-bulkWrite.json index bedd9f2b2e..de8bfe7c95 100644 --- a/test/read_write_concern/write-concern-errors/client-bulkWrite.json +++ b/test/read_write_concern/write-concern-errors/client-bulkWrite.json @@ -34,7 +34,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/client-side-encryption.json b/test/read_write_concern/write-concern-errors/client-side-encryption.json index efd5766fb3..590f2f9411 100644 --- a/test/read_write_concern/write-concern-errors/client-side-encryption.json +++ b/test/read_write_concern/write-concern-errors/client-side-encryption.json @@ -89,7 +89,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -129,7 +130,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -166,7 +168,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -208,7 +211,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -251,7 +255,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/crud.json b/test/read_write_concern/write-concern-errors/crud.json index 7a92433869..763f44023f 100644 --- a/test/read_write_concern/write-concern-errors/crud.json +++ b/test/read_write_concern/write-concern-errors/crud.json @@ -43,7 +43,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -82,7 +83,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -126,7 +128,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -170,7 +173,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -212,7 +216,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -254,7 +259,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -293,7 +299,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/db-coll-management.json b/test/read_write_concern/write-concern-errors/db-coll-management.json index 11154849ce..84f05d1936 100644 --- a/test/read_write_concern/write-concern-errors/db-coll-management.json +++ b/test/read_write_concern/write-concern-errors/db-coll-management.json @@ -57,7 +57,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -94,7 +95,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -138,7 +140,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -175,7 +178,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/findAndModify.json b/test/read_write_concern/write-concern-errors/findAndModify.json index 91dbf833aa..05e55b836b 100644 --- a/test/read_write_concern/write-concern-errors/findAndModify.json +++ b/test/read_write_concern/write-concern-errors/findAndModify.json @@ -43,7 +43,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -87,7 +88,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -129,7 +131,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/gridfs.json b/test/read_write_concern/write-concern-errors/gridfs.json index d433c68e08..bf753ee609 100644 --- a/test/read_write_concern/write-concern-errors/gridfs.json +++ b/test/read_write_concern/write-concern-errors/gridfs.json @@ -66,7 +66,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -106,7 +107,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -146,7 +148,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -185,7 +188,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -222,7 +226,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -262,7 +267,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/index-management.json b/test/read_write_concern/write-concern-errors/index-management.json index 56fee80e7a..61aafe1d4f 100644 --- a/test/read_write_concern/write-concern-errors/index-management.json +++ b/test/read_write_concern/write-concern-errors/index-management.json @@ -43,7 +43,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -92,7 +93,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } @@ -139,7 +141,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/read_write_concern/write-concern-errors/mapReduce.json b/test/read_write_concern/write-concern-errors/mapReduce.json index 7701a43934..ce5979fabe 100644 --- a/test/read_write_concern/write-concern-errors/mapReduce.json +++ b/test/read_write_concern/write-concern-errors/mapReduce.json @@ -59,7 +59,8 @@ ], "writeConcernError": { "code": 79, - "codeName": "UnknownReplWriteConcern" + "codeName": "UnknownReplWriteConcern", + "errmsg": "Triggered by failpoint" } } } diff --git a/test/test_auth.py b/test/test_auth.py index bf363267dc..40b3bc93be 100644 --- a/test/test_auth.py +++ b/test/test_auth.py @@ -239,9 +239,7 @@ def test_gssapi_threaded(self): except OperationFailure: raise SkipTest("User must be able to write.") - threads = [] - for _ in range(4): - threads.append(AutoAuthenticateThread(collection)) + threads = [AutoAuthenticateThread(collection) for _ in range(4)] for thread in threads: thread.start() for thread in threads: @@ -657,9 +655,7 @@ def test_scram_threaded(self): # The first thread to call find() will authenticate client = self.rs_or_single_client() coll = client.db.coll - threads = [] - for _ in range(4): - threads.append(AutoAuthenticateThread(coll)) + threads = [AutoAuthenticateThread(coll) for _ in range(4)] for thread in threads: thread.start() for thread in threads: diff --git a/test/test_auth_oidc.py b/test/test_auth_oidc.py index 0145c3f357..b2aa48e58f 100644 --- a/test/test_auth_oidc.py +++ b/test/test_auth_oidc.py @@ -314,7 +314,7 @@ def fetch(self, ctx): client = self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() # Close the client. client.close() @@ -558,7 +558,7 @@ def fetch(self, a): return None client = self.create_client(request_cb=RequestTokenNull()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() client.close() @@ -568,7 +568,7 @@ def fetch(self, a): return {} client = self.create_client(request_cb=CallbackInvalidToken()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() client.close() @@ -826,9 +826,7 @@ def target(): for _ in range(100): client.test.coll.find_one() - tasks = [] - for i in range(10): - tasks.append(ConcurrentRunner(target=target)) + tasks = [ConcurrentRunner(target=target) for _ in range(10)] for t in tasks: t.start() for t in tasks: @@ -852,7 +850,7 @@ def fetch(self, a): client = self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() def test_2_3_oidc_callback_returns_missing_data(self): @@ -866,7 +864,7 @@ def fetch(self, a): client = self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() def test_2_4_invalid_client_configuration_with_callback(self): diff --git a/test/test_bson.py b/test/test_bson.py index d3940bda7f..0380d1f22e 100644 --- a/test/test_bson.py +++ b/test/test_bson.py @@ -1051,7 +1051,6 @@ def assertRepr(self, obj): def test_binaryvector_repr(self): """Tests of repr(BinaryVector)""" - data = [1 / 127, -7 / 6] one = BinaryVector(data, BinaryVectorDtype.FLOAT32) self.assertEqual( @@ -1283,8 +1282,8 @@ def test_bson_regex(self): self.assertEqual(doc1, decode(doc1_bson)) # Valid Python regex, with flags. - re2 = re.compile(".*", re.I | re.M | re.S | re.U | re.X) - bson_re2 = Regex(".*", re.I | re.M | re.S | re.U | re.X) + re2 = re.compile(".*", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.UNICODE | re.VERBOSE) + bson_re2 = Regex(".*", re.IGNORECASE | re.MULTILINE | re.DOTALL | re.UNICODE | re.VERBOSE) doc2_with_re = {"r": re2} doc2_with_bson_re = {"r": bson_re2} @@ -1300,11 +1299,14 @@ def test_regex_from_native(self): self.assertEqual(".*", Regex.from_native(re.compile(".*")).pattern) self.assertEqual(0, Regex.from_native(re.compile(b"")).flags) - regex = re.compile(b"", re.I | re.L | re.M | re.S | re.X) - self.assertEqual(re.I | re.L | re.M | re.S | re.X, Regex.from_native(regex).flags) + regex = re.compile(b"", re.IGNORECASE | re.LOCALE | re.MULTILINE | re.DOTALL | re.VERBOSE) + self.assertEqual( + re.IGNORECASE | re.LOCALE | re.MULTILINE | re.DOTALL | re.VERBOSE, + Regex.from_native(regex).flags, + ) - unicode_regex = re.compile("", re.U) - self.assertEqual(re.U, Regex.from_native(unicode_regex).flags) + unicode_regex = re.compile("", re.UNICODE) + self.assertEqual(re.UNICODE, Regex.from_native(unicode_regex).flags) def test_regex_hash(self): self.assertRaises(TypeError, hash, Regex("hello")) @@ -1313,11 +1315,11 @@ def test_regex_comparison(self): re1 = Regex("a") re2 = Regex("b") self.assertNotEqual(re1, re2) - re1 = Regex("a", re.I) - re2 = Regex("a", re.M) + re1 = Regex("a", re.IGNORECASE) + re2 = Regex("a", re.MULTILINE) self.assertNotEqual(re1, re2) - re1 = Regex("a", re.I) - re2 = Regex("a", re.I) + re1 = Regex("a", re.IGNORECASE) + re2 = Regex("a", re.IGNORECASE) self.assertEqual(re1, re2) def test_exception_wrapping(self): diff --git a/test/test_bson_binary_vector.py b/test/test_bson_binary_vector.py index 4893e91961..533d8960bd 100644 --- a/test/test_bson_binary_vector.py +++ b/test/test_bson_binary_vector.py @@ -32,7 +32,8 @@ class TestBSONBinaryVector(unittest.TestCase): Tests are automatically generated on import from json files in _TEST_PATH via `create_tests`. The actual tests are defined in the inner function `run_test` - of the test generator `create_test`.""" + of the test generator `create_test`. + """ def create_test(case_spec): diff --git a/test/test_bulk.py b/test/test_bulk.py index 6c612e0edb..fd24a2496e 100644 --- a/test/test_bulk.py +++ b/test/test_bulk.py @@ -18,9 +18,7 @@ import sys import uuid -from typing import Any, Optional - -from pymongo.synchronous.mongo_client import MongoClient +from typing import TYPE_CHECKING, Any sys.path[0:0] = [""] @@ -30,11 +28,14 @@ from pymongo.common import partition_node from pymongo.errors import BulkWriteError, ConfigurationError, InvalidOperation, OperationFailure from pymongo.operations import * -from pymongo.synchronous.collection import Collection from pymongo.write_concern import WriteConcern from test import IntegrationTest, client_context, remove_all_users, unittest from test.utils_shared import wait_until +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True @@ -63,7 +64,7 @@ def assertEqualResponse(self, expected, actual): % (len(expected_upserts), len(actual_upserts)), ) - for e, a in zip(expected_upserts, actual_upserts): + for e, a in zip(expected_upserts, actual_upserts, strict=True): self.assertEqualUpsert(e, a) elif key == "writeErrors": @@ -76,7 +77,7 @@ def assertEqualResponse(self, expected, actual): % (len(expected_errors), len(actual_errors)), ) - for e, a in zip(expected_errors, actual_errors): + for e, a in zip(expected_errors, actual_errors, strict=True): self.assertEqualWriteError(e, a) else: @@ -309,8 +310,7 @@ def test_bulk_max_message_size(self): {"_id": 3, "l": "s" * (_16_MB - 10000)}, ] # Fill in the remaining ~10000 bytes with small documents. - for i in range(4, 10000): - docs.append({"_id": i}) + docs.extend({"_id": i} for i in range(4, 10000)) result = self.coll.insert_many(docs) self.assertEqual(len(docs), len(result.inserted_ids)) @@ -922,7 +922,7 @@ def test_no_remove(self): class TestBulkWriteConcern(BulkTestBase): - w: Optional[int] + w: int | None secondary: MongoClient def setUp(self): diff --git a/test/test_change_stream.py b/test/test_change_stream.py index 5fb0f6046d..9d29a80a44 100644 --- a/test/test_change_stream.py +++ b/test/test_change_stream.py @@ -90,9 +90,7 @@ def generate_invalidate_event(self, change_stream): def generate_unique_collnames(self, numcolls): """Generate numcolls collection names unique to a test.""" - collnames = [] - for idx in range(1, numcolls + 1): - collnames.append(self.id() + "_" + str(idx)) + collnames = [self.id() + "_" + str(idx) for idx in range(1, numcolls + 1)] return collnames def get_resume_token(self, invalidate=False): @@ -1070,7 +1068,7 @@ def assert_list_contents_are_subset(self, superlist, sublist): element in superlist. """ self.assertEqual(len(superlist), len(sublist)) - for sup, sub in zip(superlist, sublist): + for sup, sub in zip(superlist, sublist, strict=True): if isinstance(sub, dict): self.assert_dict_is_subset(sup, sub) continue diff --git a/test/test_client.py b/test/test_client.py index dff1bea01f..c39618eadb 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -853,7 +853,7 @@ def test_detected_environment_logging(self, mock_get_hosts): @skipIf(os.environ.get("DEBUG_LOG"), "Enabling debug logs breaks this test") @patch("pymongo.synchronous.srv_resolver._SrvResolver.get_hosts") def test_detected_environment_warning(self, mock_get_hosts): - with self._caplog.at_level(logging.WARN): + with self._caplog.at_level(logging.WARNING): normal_hosts = [ "host.cosmos.azure.com", "host.docdb.amazonaws.com", @@ -1287,7 +1287,7 @@ def test_list_databases(self): self.assertGreater(len(helper_docs), 0) self.assertEqual(len(helper_docs), len(cmd_docs)) # PYTHON-3529 Some fields may change between calls, just compare names. - for helper_doc, cmd_doc in zip(helper_docs, cmd_docs): + for helper_doc, cmd_doc in zip(helper_docs, cmd_docs, strict=True): self.assertIs(type(helper_doc), dict) self.assertEqual(helper_doc.keys(), cmd_doc.keys()) client = self.rs_or_single_client(document_class=SON) @@ -2189,7 +2189,7 @@ def test_background_connections_log_on_error(self): pool = get_pool(client) def fail_connect(*args, **kwargs): - raise Exception("failed to connect") + raise ConnectionFailure("failed to connect") pool.connect = fail_connect # Un-patch Pool.connect to break the cyclic reference. diff --git a/test/test_client_backpressure.py b/test/test_client_backpressure.py index de59a0d588..0430ee3c71 100644 --- a/test/test_client_backpressure.py +++ b/test/test_client_backpressure.py @@ -22,7 +22,9 @@ from time import perf_counter from unittest.mock import patch +from pymongo import MongoClient from pymongo.common import MAX_ADAPTIVE_RETRIES +from pymongo.cursor_shared import CursorType sys.path[0:0] = [""] @@ -162,6 +164,95 @@ def test_retry_overload_error_getMore(self): self.assertIn("RetryableError", str(error.exception)) self.assertIn("SystemOverloadedError", str(error.exception)) + @client_context.require_failCommand_appName + def test_retry_overload_error_getMore_pinned_connection(self): + # PYTHON-6262: getMores on pinned (e.g. load-balanced) connections must + # retry retryable overload errors on the pinned connection. + coll = self.db.coll + coll.delete_many({}) + coll.insert_many([{"x": 1} for _ in range(10)]) + fail_many = { + "configureFailPoint": "failCommand", + "mode": {"times": MAX_ADAPTIVE_RETRIES}, + "data": { + "failCommands": ["getMore"], + "errorCode": 462, # IngressRequestRateLimitExceeded + "errorLabels": ["RetryableError", "SystemOverloadedError"], + }, + } + with patch.object(type(self.db.client), "_should_pin_cursor", return_value=True): + # Ensure pinned getMore is retried on overload error. + cursor = coll.find(batch_size=2) + cursor.next() + # Verify the cursor actually pinned its connection. + self.assertIsNotNone(cursor._sock_mgr) + with self.fail_point(fail_many): + self.assertEqual(len(cursor.to_list()), 9) + + # Ensure pinned getMore stops retrying after MAX_ADAPTIVE_RETRIES. + fail_too_many = fail_many.copy() + fail_too_many["mode"] = {"times": MAX_ADAPTIVE_RETRIES + 1} + cursor = coll.find(batch_size=2) + cursor.next() + with self.fail_point(fail_too_many): + with self.assertRaises(PyMongoError) as error: + cursor.to_list() + + self.assertIn("RetryableError", str(error.exception)) + self.assertIn("SystemOverloadedError", str(error.exception)) + + @client_context.require_failCommand_appName + @client_context.require_exhaust_stream + def test_retry_overload_error_getMore_exhaust_receive_only(self): + # PYTHON-6262: an error on a receive-only exhaust getMore must + # surface instead of retrying a receive with no request in flight. + # Use a dedicated client: the abandoned exhaust stream leaves the + # pinned connection unusable. + uri = client_context.uri + client = MongoClient( + uri, server_api=client_context.default_client_options.get("server_api") + ) + self.addCleanup(client.close) + coll = client.get_database(self.db.name).coll + coll.delete_many({}) + coll.insert_many([{"x": 1} for _ in range(10)]) + with patch.object(type(client), "_should_pin_cursor", return_value=True): + cursor = coll.find(batch_size=2, cursor_type=CursorType.EXHAUST) + for _ in range(4): + cursor.next() + if cursor._sock_mgr and cursor._sock_mgr.more_to_come: + break + self.assertTrue(cursor._sock_mgr.more_to_come) + conn = cursor._sock_mgr.conn + orig_receive = type(conn).receive_message + receives = 0 + + def fail_receive_only(conn, request_id): + # Consume the streamed reply, then fail like a retryable + # overload reply would. + reply = orig_receive(conn, request_id) + if request_id is None: + nonlocal receives + receives += 1 + raise OperationFailure( + "getMore overload", + 462, + { + "errorLabels": ["RetryableError", "SystemOverloadedError"], + "baseBackoffMS": 10, + }, + ) + return reply + + with patch.object(type(conn), "receive_message", fail_receive_only): + with self.assertRaises(PyMongoError) as error: + cursor.to_list() + + # The failed receive ended the stream: no request-less retry. + self.assertEqual(receives, 1) + self.assertIn("RetryableError", str(error.exception)) + self.assertIn("SystemOverloadedError", str(error.exception)) + # Prose tests. class TestClientBackpressure(IntegrationTest): diff --git a/test/test_client_bulk_write.py b/test/test_client_bulk_write.py index a7bf8ee777..ef2cdec8c7 100644 --- a/test/test_client_bulk_write.py +++ b/test/test_client_bulk_write.py @@ -98,18 +98,18 @@ def test_3_batch_splits_if_num_operations_too_large(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append(InsertOne(namespace="db.coll", document={"a": "b"})) + models = [ + InsertOne(namespace="db.coll", document={"a": "b"}) + for _ in range(self.max_write_batch_size + 1) + ] self.addCleanup(client.db["coll"].drop) result = client.bulk_write(models=models) self.assertEqual(result.inserted_count, self.max_write_batch_size + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -122,25 +122,23 @@ def test_4_batch_splits_if_ops_payload_too_large(self): listener = OvertCommandListener() client = self.rs_or_single_client(event_listeners=[listener]) - models = [] num_models = int(self.max_message_size_bytes / self.max_bson_object_size + 1) b_repeated = "b" * (self.max_bson_object_size - 500) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] self.addCleanup(client.db["coll"].drop) result = client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -166,14 +164,13 @@ def test_5_collects_write_concern_errors_across_batches(self): }, } with self.fail_point(fail_command): - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"a": "b"}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": "b"}, ) + for _ in range(self.max_write_batch_size + 1) + ] self.addCleanup(client.db["coll"].drop) with self.assertRaises(ClientBulkWriteException) as context: @@ -184,10 +181,9 @@ def test_5_collects_write_concern_errors_across_batches(self): context.exception.partial_result.inserted_count, self.max_write_batch_size + 1 ) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) @client_context.require_version_min(8, 0, 0, -24) @@ -200,23 +196,21 @@ def test_6_collects_write_errors_across_batches_unordered(self): collection.drop() collection.insert_one(document={"_id": 1}) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"_id": 1}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"_id": 1}, ) + for _ in range(self.max_write_batch_size + 1) + ] with self.assertRaises(ClientBulkWriteException) as context: client.bulk_write(models=models, ordered=False) self.assertEqual(len(context.exception.write_errors), self.max_write_batch_size + 1) # type: ignore[arg-type] - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) @client_context.require_version_min(8, 0, 0, -24) @@ -229,23 +223,21 @@ def test_6_collects_write_errors_across_batches_ordered(self): collection.drop() collection.insert_one(document={"_id": 1}) - models = [] - for _ in range(self.max_write_batch_size + 1): - models.append( - InsertOne( - namespace="db.coll", - document={"_id": 1}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"_id": 1}, ) + for _ in range(self.max_write_batch_size + 1) + ] with self.assertRaises(ClientBulkWriteException) as context: client.bulk_write(models=models, ordered=True) self.assertEqual(len(context.exception.write_errors), 1) # type: ignore[arg-type] - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 1) @client_context.require_version_min(8, 0, 0, -24) @@ -418,15 +410,14 @@ def _setup_namespace_test_models(self): num_models = ops_bytes // self.max_bson_object_size remainder_bytes = ops_bytes % self.max_bson_object_size - models = [] b_repeated = "b" * (self.max_bson_object_size - _OPERATION_DOC_BYTES) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] if remainder_bytes >= _NAMESPACE_DOC_BYTES: num_models += 1 b_repeated = "b" * (remainder_bytes - _OPERATION_DOC_BYTES) @@ -456,10 +447,9 @@ def test_11_no_batch_splits_if_new_namespace_is_not_too_large(self): result = client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 1) event = bulk_write_events[0] @@ -489,10 +479,9 @@ def test_11_batch_splits_if_new_namespace_is_too_large(self): result = client.bulk_write(models=models) self.assertEqual(result.inserted_count, num_models + 1) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) first_event, second_event = bulk_write_events @@ -648,16 +637,15 @@ def test_timeout_in_multi_batch_bulk_write(self): "data": {"failCommands": ["bulkWrite"], "blockConnection": True, "blockTimeMS": 1010}, } with self.fail_point(fail_command): - models = [] num_models = int(self.max_message_size_bytes / self.max_bson_object_size + 1) b_repeated = "b" * (self.max_bson_object_size - _OVERHEAD) - for _ in range(num_models): - models.append( - InsertOne( - namespace="db.coll", - document={"a": b_repeated}, - ) + models = [ + InsertOne( + namespace="db.coll", + document={"a": b_repeated}, ) + for _ in range(num_models) + ] listener = OvertCommandListener() client = self.rs_or_single_client( @@ -674,8 +662,7 @@ def test_timeout_in_multi_batch_bulk_write(self): client.bulk_write(models=models) self.assertIsInstance(context.exception.error, NetworkTimeout) - bulk_write_events = [] - for event in listener.started_events: - if event.command_name == "bulkWrite": - bulk_write_events.append(event) + bulk_write_events = [ + event for event in listener.started_events if event.command_name == "bulkWrite" + ] self.assertEqual(len(bulk_write_events), 2) diff --git a/test/test_client_metadata.py b/test/test_client_metadata.py index b35e3f0bc7..1af37ae46b 100644 --- a/test/test_client_metadata.py +++ b/test/test_client_metadata.py @@ -18,17 +18,19 @@ import pathlib import time import unittest -from typing import Any, Optional, cast +from typing import TYPE_CHECKING, Any, cast import pytest -from pymongo import MongoClient from pymongo.driver_info import DriverInfo from pymongo.monitoring import ConnectionClosedEvent from test import IntegrationTest from test.unified_format import generate_test_classes, get_test_path from test.utils_shared import CMAPListener +if TYPE_CHECKING: + from pymongo import MongoClient + try: from mockupdb import MockupDB, OpMsgReply @@ -67,10 +69,10 @@ def respond(r): def send_ping_and_get_metadata( self, client: MongoClient, is_handshake: bool - ) -> tuple[str, Optional[str], Optional[str], dict[str, Any]]: + ) -> tuple[str, str | None, str | None, dict[str, Any]]: # reset if handshake request if is_handshake: - self.handshake_req: Optional[dict] = None + self.handshake_req: dict | None = None client.admin.command("ping") metadata = _get_handshake_driver_info(self.handshake_req) @@ -86,8 +88,8 @@ def check_metadata_added( self, client: MongoClient, add_name: str, - add_version: Optional[str], - add_platform: Optional[str], + add_version: str | None, + add_platform: str | None, ) -> None: # send initial metadata name, version, platform, metadata = self.send_ping_and_get_metadata(client, True) @@ -196,7 +198,7 @@ def test_doesnt_update_established_connections(self): add_name, add_version, add_platform = "framework", "2.0", "Framework Platform" client.append_metadata(DriverInfo(add_name, add_version, add_platform)) # check new data isn't sent - self.handshake_req: Optional[dict] = None + self.handshake_req: dict | None = None client.admin.command("ping") self.assertIsNone(self.handshake_req) self.assertEqual(listener.event_count(ConnectionClosedEvent), 0) @@ -295,11 +297,11 @@ def test_10_entries_in_driver_name_and_driver_version_correspond_by_index(self): self.assertIsNotNone(name0) self.assertIsNotNone(version0) - version0 = cast(str, version0) + version0 = cast("str", version0) driver_name = name0.split("|")[0] driver_version = version0.split("|")[0] - def resolve(value: Optional[str]) -> Optional[str]: + def resolve(value: str | None) -> str | None: if value is None: return None return value.format(driver_name=driver_name, driver_version=driver_version) diff --git a/test/test_collection.py b/test/test_collection.py index 58589f5916..db6f5f9fb7 100644 --- a/test/test_collection.py +++ b/test/test_collection.py @@ -23,9 +23,8 @@ from codecs import utf_8_decode from collections import defaultdict from collections.abc import Iterable -from typing import Any, no_type_check +from typing import TYPE_CHECKING, Any, no_type_check -from pymongo.synchronous.database import Database from pymongo.synchronous.helpers import next from test.utils import get_pool @@ -63,7 +62,6 @@ ) from pymongo.synchronous.collection import Collection, ReturnDocument from pymongo.synchronous.command_cursor import CommandCursor -from pymongo.synchronous.mongo_client import MongoClient from pymongo.write_concern import WriteConcern from test import ( # TODO: fix sync imports in PYTHON-4528 IntegrationTest, @@ -79,6 +77,10 @@ ) from test.version import Version +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True @@ -494,7 +496,7 @@ def test_index_2dsphere(self): db.coll.drop_indexes() self.assertEqual("geo_2dsphere", db.coll.create_index([("geo", GEOSPHERE)])) - for dummy, info in (db.coll.index_information()).items(): + for info in (db.coll.index_information()).values(): field, idx_type = info["key"][0] if field == "geo" and idx_type == "2dsphere": break @@ -513,7 +515,7 @@ def test_index_hashed(self): db.coll.drop_indexes() self.assertEqual("a_hashed", db.coll.create_index([("a", HASHED)])) - for dummy, info in (db.coll.index_information()).items(): + for info in (db.coll.index_information()).values(): field, idx_type = info["key"][0] if field == "a" and idx_type == "hashed": break diff --git a/test/test_comment.py b/test/test_comment.py index 07a10b02ca..49751daa8f 100644 --- a/test/test_comment.py +++ b/test/test_comment.py @@ -55,7 +55,7 @@ def _test_ops( "signature of function %s" % (h.__name__), ) self.assertEqual( - inspect.signature(h).parameters["comment"].annotation, "Optional[Any]" + inspect.signature(h).parameters["comment"].annotation, "Any | None" ) if isinstance(maybe_cursor, CommandCursor): maybe_cursor.close() diff --git a/test/test_connection_monitoring.py b/test/test_connection_monitoring.py index 58f2fe80cb..042812ac69 100644 --- a/test/test_connection_monitoring.py +++ b/test/test_connection_monitoring.py @@ -199,7 +199,7 @@ def actual_events(self, ignore): def check_events(self, events, ignore): """Check the events of a test.""" actual_events = self.actual_events(ignore) - for actual, expected in zip(actual_events, events): + for actual, expected in zip(actual_events, events, strict=False): self.logs.append(f"Checking event actual: {actual!r} vs expected: {expected!r}") self.check_event(actual, expected) diff --git a/test/test_connections_survive_primary_stepdown_spec.py b/test/test_connections_survive_primary_stepdown_spec.py index dfcec79322..e704914267 100644 --- a/test/test_connections_survive_primary_stepdown_spec.py +++ b/test/test_connections_survive_primary_stepdown_spec.py @@ -22,10 +22,11 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson import SON from pymongo import monitoring from pymongo.errors import NotPrimaryError -from pymongo.synchronous.collection import Collection from pymongo.write_concern import WriteConcern from test import ( IntegrationTest, @@ -37,6 +38,9 @@ CMAPListener, ) +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + _IS_SYNC = True diff --git a/test/test_cursor.py b/test/test_cursor.py index 5ce277e8a9..af7ff17214 100644 --- a/test/test_cursor.py +++ b/test/test_cursor.py @@ -26,7 +26,7 @@ import sys import threading import time -from typing import Any +from typing import TYPE_CHECKING, Any import pymongo @@ -38,7 +38,6 @@ from pymongo import ASCENDING, DESCENDING from pymongo.collation import Collation from pymongo.errors import ExecutionTimeout, InvalidOperation, OperationFailure, PyMongoError -from pymongo.operations import _IndexList from pymongo.read_concern import ReadConcern from pymongo.read_preferences import ReadPreference from pymongo.synchronous.cursor import Cursor, CursorType @@ -55,6 +54,9 @@ wait_until, ) +if TYPE_CHECKING: + from pymongo.operations import _IndexList + _IS_SYNC = True @@ -1030,18 +1032,18 @@ def test_getitem_slice_index(self): self.assertRaises(IndexError, lambda: self.db.coll.find()[-1:]) self.assertRaises(IndexError, lambda: self.db.coll.find()[1:2:2]) - for a, b in zip(count(0), self.db.coll.find()): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find(), strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(100, len(list(self.db.coll.find()[0:]))) # type: ignore[call-overload] - for a, b in zip(count(0), self.db.coll.find()[0:]): # type: ignore[call-overload] + for a, b in zip(count(0), self.db.coll.find()[0:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) - for a, b in zip(count(99), self.db.coll.find()[99:]): # type: ignore[call-overload] + for a, b in zip(count(99), self.db.coll.find()[99:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) for _i in self.db.coll.find()[1000:]: @@ -1049,19 +1051,19 @@ def test_getitem_slice_index(self): self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] self.assertEqual(5, len(list(self.db.coll.find()[20:25]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[20:25]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[20:25], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[40:45][20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[40:45][20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45][20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find()[40:45].limit(0).skip(20)))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20)): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find()[40:45].limit(0).skip(20), strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(80, len(list(self.db.coll.find().limit(10).skip(40)[20:]))) # type: ignore[call-overload] - for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:]): # type: ignore[call-overload] + for a, b in zip(count(20), self.db.coll.find().limit(10).skip(40)[20:], strict=False): # type: ignore[call-overload] self.assertEqual(a, b["i"]) self.assertEqual(1, len(list(self.db.coll.find()[:1]))) # type: ignore[call-overload] diff --git a/test/test_custom_types.py b/test/test_custom_types.py index 34f0fb31bc..c395c64ccf 100644 --- a/test/test_custom_types.py +++ b/test/test_custom_types.py @@ -145,9 +145,7 @@ def test_encode_decode_roundtrip(self): @no_type_check def test_decode_all(self): - documents = [] - for dec in range(3): - documents.append({"average": Decimal(f"56.4{dec}")}) + documents = [{"average": Decimal(f"56.4{dec}")} for dec in range(3)] bsonstream = b"" for doc in documents: @@ -181,7 +179,9 @@ def _generate_multidocument_bson_stream(self): @no_type_check def test_decode_iter(self): expected, bson_data = self._generate_multidocument_bson_stream() - for expected_doc, decoded_doc in zip(expected, decode_iter(bson_data, self.codecopts)): + for expected_doc, decoded_doc in zip( + expected, decode_iter(bson_data, self.codecopts), strict=True + ): self.assertEqual(expected_doc, decoded_doc) @no_type_check @@ -191,7 +191,9 @@ def test_decode_file_iter(self): fileobj.write(bson_data) fileobj.seek(0) - for expected_doc, decoded_doc in zip(expected, decode_file_iter(fileobj, self.codecopts)): + for expected_doc, decoded_doc in zip( + expected, decode_file_iter(fileobj, self.codecopts), strict=True + ): self.assertEqual(expected_doc, decoded_doc) fileobj.close() diff --git a/test/test_database.py b/test/test_database.py index b6e5170ff5..bced1879ba 100644 --- a/test/test_database.py +++ b/test/test_database.py @@ -19,7 +19,7 @@ import re import sys from collections.abc import Iterable, Mapping -from typing import Any, Union +from typing import Any from pymongo.synchronous.command_cursor import CommandCursor @@ -211,7 +211,7 @@ def test_list_collection_names_filter(self): db.capped.insert_one({}) db.non_capped.insert_one({}) self.addCleanup(client.drop_database, db.name) - filter: Union[None, Mapping[str, Any]] + filter: Mapping[str, Any] | None # Should not send nameOnly. for filter in ({"options.capped": True}, {"options.capped": True, "name": "capped"}): listener.reset() @@ -482,7 +482,7 @@ def test_id_ordering(self): ) cursor = db.coll.find() for x in cursor: - for k, _v in x.items(): + for k in x.keys(): self.assertEqual(k, "_id") break diff --git a/test/test_discovery_and_monitoring.py b/test/test_discovery_and_monitoring.py index face947397..7407f61664 100644 --- a/test/test_discovery_and_monitoring.py +++ b/test/test_discovery_and_monitoring.py @@ -20,11 +20,14 @@ import os import platform import socketserver +import struct import sys import threading import time +import unittest from asyncio import StreamReader, StreamWriter from pathlib import Path +from typing import Any from pymongo.errors import ConnectionFailure from pymongo.operations import _Op @@ -38,6 +41,8 @@ from unittest.mock import patch from bson import Timestamp, json_util +from bson import decode as bson_decode +from bson import encode as bson_encode from pymongo import common, monitoring from pymongo.errors import ( AutoReconnect, @@ -58,7 +63,7 @@ from pymongo.synchronous.settings import TopologySettings from pymongo.synchronous.topology import Topology from pymongo.synchronous.uri_parser import parse_uri -from pymongo.topology_description import TOPOLOGY_TYPE +from pymongo.topology_description import TOPOLOGY_TYPE, TopologyDescription from pymongo.topology_shared import _ErrorContext from test import ( IntegrationTest, @@ -350,9 +355,7 @@ def insert_command(i): except AutoReconnect: pass - tasks = [] - for i in range(N_TASKS): - tasks.append(ConcurrentRunner(target=insert_command, args=(i,))) + tasks = [ConcurrentRunner(target=insert_command, args=(i,)) for i in range(N_TASKS)] for t in tasks: t.start() for t in tasks: @@ -530,9 +533,7 @@ def target(): pass # Run 100 parallel operations that contend for connections. - tasks = [] - for _ in range(100): - tasks.append(ConcurrentRunner(target=target)) + tasks = [ConcurrentRunner(target=target) for _ in range(100)] for t in tasks: t.start() for t in tasks: @@ -553,7 +554,7 @@ def test_rtt_connection_is_enabled_stream(self): client.admin.command("ping") def predicate(): - for _, server in client._topology._servers.items(): + for server in client._topology._servers.values(): monitor = server._monitor if not monitor._stream: return False @@ -595,7 +596,7 @@ def test_rtt_connection_is_disabled_auto(self): def assert_rtt_connection_is_disabled(self, client): client.admin.command("ping") - for _, server in client._topology._servers.items(): + for server in client._topology._servers.values(): monitor = server._monitor self.assertFalse(monitor._stream) if _IS_SYNC: @@ -676,6 +677,154 @@ def handle_client(reader: StreamReader, writer: StreamWriter): ) +class TestMonitorRecoversAfterSelfRemoval(UnitTest): + @unittest.skipUnless(not _IS_SYNC, "PYTHON-6226: monitor task self-cancellation is async-only") + def test_monitor_recovers_after_self_removal(self): + # Regression test for PYTHON-6226: a monitor that closed its own + # server used to cancel itself, leaving the client stuck in + # ReplicaSetNoPrimary. The client must recover. + + # Fake two-node replica set on ephemeral ports. + role: dict[int, str] = {} + hosts: list[str] = [] + + def make_handler(port_box): + def handle(reader: StreamReader, writer: StreamWriter): + port = port_box["port"] + try: + while True: + length, req_id, _, _ = struct.unpack( + # The ignore is for the sync mirror, where + # unasync turns this read into a bare call. + " dict[str, StringOpts]: - """Pass StringOpts under the name the installed pymongocrypt accepts. - - pymongocrypt renamed ``text_opts`` to ``string_opts`` in 1.19 and takes only - one of the two, and the preview query types still run against pymongocrypt - before 1.19, so both spellings are in play across the matrix. - """ - return {encryption._string_opts_kwarg(): StringOpts(**kwargs)} - - -class TestStringOptsDeprecation(PyMongoTestCase): - def test_text_opts_is_still_re_exported(self): - # TextOpts is deprecated, not removed, so it must stay importable from - # the encryption module for the deprecation period. - self.assertIs(encryption.TextOpts, TextOpts) - - def test_text_opts_is_deprecated(self): - with self.assertWarns(DeprecationWarning): - opts = TextOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - self.assertIsInstance(opts, StringOpts) - self.assertEqual( - StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}).document, - opts.document, - ) - - def test_resolve_string_opts_no_opts(self): - self.assertIsNone(encryption._resolve_string_opts(None, None)) - - def test_resolve_string_opts_rejects_both(self): - string_opts = StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - with self.assertRaises(ConfigurationError): - encryption._resolve_string_opts(string_opts, string_opts) - - @unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed") - def test_resolve_string_opts_follows_pymongocrypt(self): - # pymongocrypt accepts only one of the two names per release: text_opts - # through 1.18 and string_opts from 1.19. Passing the name the - # installed binding does not support is an error rather than a silent - # alias, so assert against the resolved name. - string_opts = StringOpts(prefix={"strMinQueryLength": 2, "strMaxQueryLength": 10}) - if encryption._string_opts_kwarg() == "string_opts": - supported, unsupported = (string_opts, None), (None, string_opts) - else: - supported, unsupported = (None, string_opts), (string_opts, None) - self.assertIs(encryption._resolve_string_opts(*supported), string_opts) - with self.assertRaises(ConfigurationError): - encryption._resolve_string_opts(*unsupported) - - @unittest.skipUnless(_HAVE_PYMONGOCRYPT, "pymongocrypt is not installed") - def test_string_opts_kwarg_matches_binding(self): - # The resolved name is passed straight through to pymongocrypt, so - # assert it against the installed binding here: a mismatch then fails - # without a server, rather than only in the prose suite. - params = inspect.signature(encryption.ExplicitEncrypter.encrypt).parameters - self.assertIn(encryption._string_opts_kwarg(), params) - - class EncryptionIntegrationTest(IntegrationTest): """Base class for encryption integration tests.""" @@ -323,8 +267,8 @@ def create_client_encryption( key_vault_namespace: str, key_vault_client: MongoClient, codec_options: CodecOptions, - kms_tls_options: Optional[Mapping[str, Any]] = None, - kms_connect_callback: Optional[Any] = None, + kms_tls_options: Mapping[str, Any] | None = None, + kms_connect_callback: Any | None = None, ): client_encryption = ClientEncryption( kms_providers, @@ -344,8 +288,8 @@ def unmanaged_create_client_encryption( key_vault_namespace: str, key_vault_client: MongoClient, codec_options: CodecOptions, - kms_tls_options: Optional[Mapping[str, Any]] = None, - kms_connect_callback: Optional[Any] = None, + kms_tls_options: Mapping[str, Any] | None = None, + kms_connect_callback: Any | None = None, ): client_encryption = ClientEncryption( kms_providers, @@ -1445,7 +1389,7 @@ def _test_explicit(self, expectation): self._setup() client_encryption = self.create_client_encryption( self.KMS_PROVIDER_MAP, # type: ignore[arg-type] - ".".join([self.KEYVAULT_DB, self.KEYVAULT_COLL]), + f"{self.KEYVAULT_DB}.{self.KEYVAULT_COLL}", client_context.client, OPTS, ) @@ -1463,7 +1407,7 @@ def _test_automatic(self, expectation_extjson, payload): self._setup() encrypted_db = "db" encrypted_coll = "coll" - keyvault_namespace = ".".join([self.KEYVAULT_DB, self.KEYVAULT_COLL]) + keyvault_namespace = f"{self.KEYVAULT_DB}.{self.KEYVAULT_COLL}" encryption_opts = AutoEncryptionOpts( self.KMS_PROVIDER_MAP, # type: ignore[arg-type] @@ -2892,7 +2836,7 @@ def run_expression_find( self.encrypted_client.db.explicit_encryption.find(find_payload).to_list(), key=lambda x: x["_id"], ) - for elem, expected in zip(sorted_find, expected_elems): + for elem, expected in zip(sorted_find, expected_elems, strict=True): self.assertEqual(elem[f"encrypted{name}"], expected) def run_test_cases(self, name, range_opts, cast_func): @@ -3295,6 +3239,7 @@ def test_mixed_null_keyids(self): for val, key in zip( ["123-45-6789", "11/22/1963", "My secret", "New Mexico, 87104"], [field["keyId"] for field in ef["fields"]], + strict=True, ) ] coll.insert_one( @@ -3391,43 +3336,30 @@ def _libmongocrypt_at_least(*version): return Version.from_string(libmongocrypt_version()) >= Version(*version) -# The minimum libmongocrypt version required by each string query type, declared -# in one place so the test gates and the changelog agree. Support landed per -# query type rather than all at once (see the libmongocrypt changelog): -# 1.18.1 - fixes caseSensitive/diacriticSensitive handling for "textPreview". -# 1.19.0 - the "string" algorithm replaces "textPreview"; prefix and suffix go -# stable; prefixPreview and suffixPreview are removed. -# 1.19.1 - prefixPreview and suffixPreview are restored. +# The minimum libmongocrypt version required by each GA string query type, +# declared in one place so the test gates and the changelog agree. Support +# landed per query type rather than all at once (see the libmongocrypt +# changelog): +# 1.19.0 - the "string" algorithm replaces "textPreview"; prefix and suffix +# go stable. # 1.20.0 - substring goes stable. +# 1.21.0 - the beta prefixPreview/suffixPreview/substringPreview query types +# became a runtime error (MONGOCRYPT-938) and were dropped in +# PYTHON-5959. _STRING_QUERY_MIN_LIBMONGOCRYPT = { "prefix": (1, 19, 0), "suffix": (1, 19, 0), "substring": (1, 20, 0), - "prefixPreview": (1, 18, 1), - "suffixPreview": (1, 18, 1), - "substringPreview": (1, 18, 1), } -# prefixPreview and suffixPreview were removed in 1.19.0 and restored in 1.19.1, -# so that one release is a hole rather than a floor. -_PREVIEW_REMOVED_IN = (1, 19, 0) - -# No pymongocrypt release ships libmongocrypt 1.19.0+, so the GA query types can -# only run against a master build; setup_tests.py pins the released binding for -# the 8.x preview tasks alone. Do not collapse that gate: the released binding -# still spells the parameter text_opts, and dropping back to it would silently -# stop exercising the GA path. - # https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/tests/README.md#27-string-explicit-encryption class TestStringExplicitEncryptionProse(EncryptionIntegrationTest): - # The GA collections require server 9.0+, the preview collections require - # server pre-9.0. Setup encrypts with the "String" algorithm on 9.0+ and the - # deprecated "textPreview" algorithm on earlier servers, since "String" was - # only introduced in libmongocrypt 1.19.0. + # The GA collections require server 9.0+, where the "String" algorithm and + # the GA query types are supported. @client_context.require_no_standalone - @client_context.require_version_min(8, 2, -1) - @client_context.require_libmongocrypt_min(1, 18, 1) + @client_context.require_version_min(9, 0, -1) + @client_context.require_libmongocrypt_min(1, 19, 0) @client_context.require_pymongocrypt_min(1, 16, 0) def setUp(self): super().setUp() @@ -3463,39 +3395,18 @@ def setUp(self): ) ) - # The GA query types ("prefix", "suffix", "substring") require server - # 9.0+, which in turn dropped the preview query types. - self.is_ga = client_context.version.at_least(9, 0, -1) - # The "String" algorithm was added in libmongocrypt 1.19.0. Servers - # before 9.0 are tested against libmongocrypt 1.18.x, where the preview - # query types are only usable via the deprecated "textPreview" - # algorithm, so pick whichever the running combination supports. - self.algorithm = ( - Algorithm.STRING if _libmongocrypt_at_least(1, 19, 0) else Algorithm.TEXTPREVIEW - ) - # The GA query types need the "String" algorithm, so skip before setup - # encrypts anything rather than erroring on an unsupported combination. - if self.is_ga and not _libmongocrypt_at_least(1, 19, 0): - raise unittest.SkipTest("server 9.0+ string queries require libmongocrypt 1.19.0+") # Substring went stable in a later libmongocrypt than prefix and suffix, # so its fixture is only built where the query type exists. Otherwise # setup would fail before the substring cases could skip, taking the # prefix and suffix cases down with it. - self.has_substring = _libmongocrypt_at_least( - *_STRING_QUERY_MIN_LIBMONGOCRYPT["substring" if self.is_ga else "substringPreview"] - ) + self.has_substring = _libmongocrypt_at_least(*_STRING_QUERY_MIN_LIBMONGOCRYPT["substring"]) # Using QE CreateCollection() and Collection.Drop(), drop and create the # collections with majority write concern. db = self.client_encrypted.db - if self.is_ga: - collections = ["prefix-suffix", "prefix-suffix-ci-di"] - if self.has_substring: - collections += ["substring", "substring-ci-di"] - else: - collections = ["prefix-suffix-preview"] - if self.has_substring: - collections += ["substring-preview"] + collections = ["prefix-suffix", "prefix-suffix-ci-di"] + if self.has_substring: + collections += ["substring", "substring-ci-di"] for name in collections: db.drop_collection(name) self.client_encryption.create_encrypted_collection( @@ -3509,9 +3420,9 @@ def setUp(self): encrypted_value = self.client_encryption.encrypt( "foobarbaz", key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, contention_factor=0, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), @@ -3519,33 +3430,25 @@ def setUp(self): ), ) # Use explicitEncryptedClient to insert the following document into - # db.prefix-suffix (if created) and db.prefix-suffix-preview (if created) - # with majority write concern. - self._insert( - "prefix-suffix" if self.is_ga else "prefix-suffix-preview", - {"_id": 0, "encryptedText": encrypted_value}, - ) + # db.prefix-suffix with majority write concern. + self._insert("prefix-suffix", {"_id": 0, "encryptedText": encrypted_value}) if self.has_substring: # Use clientEncryption to encrypt the string "foobarbaz" with the following EncryptOpts. encrypted_value = self.client_encryption.encrypt( "foobarbaz", key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, contention_factor=0, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ), ) # Use explicitEncryptedClient to insert the following document into - # db.substring (if created) and db.substring-preview (if created) with - # majority write concern. - self._insert( - "substring" if self.is_ga else "substring-preview", - {"_id": 0, "encryptedText": encrypted_value}, - ) + # db.substring with majority write concern. + self._insert("substring", {"_id": 0, "encryptedText": encrypted_value}) def _insert(self, collection, document, client=None): """Insert a document with majority write concern.""" @@ -3560,45 +3463,15 @@ def _require_query_type(self, query_type): raise unittest.SkipTest( f"queryType={query_type} requires libmongocrypt {'.'.join(map(str, required))}+" ) - if query_type in ("prefixPreview", "suffixPreview") and ( - _libmongocrypt_at_least(*_PREVIEW_REMOVED_IN) and not _libmongocrypt_at_least(1, 19, 1) - ): - raise unittest.SkipTest(f"queryType={query_type} was removed in libmongocrypt 1.19.0") - - def _params(self, kind): - """Return the (query_type, collection) pair to run a case against. - - Each case runs against the GA query type on server 9.0+ and against the - preview query type on earlier servers, skipping when the installed - libmongocrypt is too old for the applicable variant. - """ - base = "substring" if kind == "substring" else "prefix-suffix" - if self.is_ga: - query_type, collection = kind, base - else: - query_type, collection = f"{kind}Preview", f"{base}-preview" - self._require_query_type(query_type) - return query_type, collection - - def _require_ga(self, *query_types): - """Skip a case that only applies to the GA query types. - - Gates on each query type the case exercises, since substring support - landed in a later libmongocrypt than prefix and suffix. - """ - if not self.is_ga: - raise unittest.SkipTest("requires server 9.0+") - for query_type in query_types: - self._require_query_type(query_type) def _encrypt(self, value, query_type=None, **string_opts): return self.client_encryption.encrypt( value, key_id=self.key1_id, - algorithm=self.algorithm, + algorithm=Algorithm.STRING, query_type=query_type, contention_factor=0, - **_string_opts_kwargs(**string_opts), + string_opts=StringOpts(**string_opts), ) def _find(self, collection, filter): @@ -3608,18 +3481,19 @@ def _find(self, collection, filter): return value def test_01_can_find_a_document_by_prefix(self): - query_type, collection = self._params("prefix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "foo". encrypted_value = self._encrypt( "foo", - query_type=query_type, + query_type=QueryType.PREFIX, case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "prefix-suffix", { "$expr": { "$encStrStartsWith": {"input": "$encryptedText", "prefix": encrypted_value} @@ -3630,36 +3504,38 @@ def test_01_can_find_a_document_by_prefix(self): self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) def test_02_can_find_a_document_by_suffix(self): - query_type, collection = self._params("suffix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("suffix") # Use clientEncryption.encrypt() to encrypt the string "baz". encrypted_value = self._encrypt( "baz", - query_type=query_type, + query_type=QueryType.SUFFIX, case_sensitive=True, diacritic_sensitive=True, suffix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "prefix-suffix", {"$expr": {"$encStrEndsWith": {"input": "$encryptedText", "suffix": encrypted_value}}}, ) # Assert the following document is returned. self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) def test_03_no_document_found_by_prefix(self): - query_type, collection = self._params("prefix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "baz". encrypted_value = self._encrypt( "baz", - query_type=query_type, + query_type=QueryType.PREFIX, case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "prefix-suffix", { "$expr": { "$encStrStartsWith": {"input": "$encryptedText", "prefix": encrypted_value} @@ -3670,36 +3546,38 @@ def test_03_no_document_found_by_prefix(self): self.assertIsNone(value) def test_04_no_document_found_by_suffix(self): - query_type, collection = self._params("suffix") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.19.0+. + self._require_query_type("suffix") # Use clientEncryption.encrypt() to encrypt the string "foo". encrypted_value = self._encrypt( "foo", - query_type=query_type, + query_type=QueryType.SUFFIX, case_sensitive=True, diacritic_sensitive=True, suffix=dict(strMaxQueryLength=10, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "prefix-suffix", {"$expr": {"$encStrEndsWith": {"input": "$encryptedText", "suffix": encrypted_value}}}, ) # Assert that no documents are returned. self.assertIsNone(value) def test_05_can_find_a_document_by_substring(self): - query_type, collection = self._params("substring") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.20.0+. + self._require_query_type("substring") # Use clientEncryption.encrypt() to encrypt the string "bar". encrypted_value = self._encrypt( "bar", - query_type=query_type, + query_type=QueryType.SUBSTRING, case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "substring", { "$expr": { "$encStrContains": {"input": "$encryptedText", "substring": encrypted_value} @@ -3710,18 +3588,19 @@ def test_05_can_find_a_document_by_substring(self): self.assertEqual(value, {"_id": 0, "encryptedText": "foobarbaz"}) def test_06_no_document_found_by_substring(self): - query_type, collection = self._params("substring") + # Requires MongoDB server 9.0.0+ and libmongocrypt 1.20.0+. + self._require_query_type("substring") # Use clientEncryption.encrypt() to encrypt the string "qux". encrypted_value = self._encrypt( "qux", - query_type=query_type, + query_type=QueryType.SUBSTRING, case_sensitive=True, diacritic_sensitive=True, substring=dict(strMaxLength=10, strMaxQueryLength=6, strMinQueryLength=2), ) # Use explicitEncryptedClient to run a "find" operation. value = self._find( - collection, + "substring", { "$expr": { "$encStrContains": {"input": "$encryptedText", "substring": encrypted_value} @@ -3734,7 +3613,7 @@ def test_06_no_document_found_by_substring(self): def test_07_contentionFactor_is_required(self): from pymongocrypt.errors import MongoCryptError - self._require_ga("prefix") + self._require_query_type("prefix") # Use clientEncryption.encrypt() to encrypt the string "foo" without contentionFactor. with self.assertRaises(EncryptionError) as ctx: self.client_encryption.encrypt( @@ -3742,7 +3621,7 @@ def test_07_contentionFactor_is_required(self): key_id=self.key1_id, algorithm=Algorithm.STRING, query_type=QueryType.PREFIX, - **_string_opts_kwargs( + string_opts=StringOpts( case_sensitive=True, diacritic_sensitive=True, prefix=dict(strMaxQueryLength=10, strMinQueryLength=2), @@ -3755,7 +3634,8 @@ def test_07_contentionFactor_is_required(self): def test_08_case_insensitive_prefix_and_suffix(self): # This is a regression test for DRIVERS-3470. - self._require_ga("prefix", "suffix") + self._require_query_type("prefix") + self._require_query_type("suffix") # Use autoEncryptedClient to insert the following document. self._insert( "prefix-suffix-ci-di", {"encryptedText": "BingQiLin"}, self.client_auto_encrypted @@ -3798,7 +3678,8 @@ def test_08_case_insensitive_prefix_and_suffix(self): def test_09_diacritic_insensitive_prefix_and_suffix(self): # This is a regression test for DRIVERS-3470. - self._require_ga("prefix", "suffix") + self._require_query_type("prefix") + self._require_query_type("suffix") # Use autoEncryptedClient to insert the following document. self._insert( "prefix-suffix-ci-di", {"encryptedText": "cafébarbäz"}, self.client_auto_encrypted @@ -3841,7 +3722,7 @@ def test_09_diacritic_insensitive_prefix_and_suffix(self): def test_10_case_insensitive_substring(self): # This is a regression test for DRIVERS-3470. - self._require_ga("substring") + self._require_query_type("substring") # Use autoEncryptedClient to insert the following document. self._insert("substring-ci-di", {"encryptedText": "FooBarBaz"}, self.client_auto_encrypted) # Use clientEncryption.encrypt() to encrypt the string "bar". @@ -3866,7 +3747,7 @@ def test_10_case_insensitive_substring(self): def test_11_diacritic_insensitive_substring(self): # This is a regression test for DRIVERS-3470. - self._require_ga("substring") + self._require_query_type("substring") # Use autoEncryptedClient to insert the following document. self._insert("substring-ci-di", {"encryptedText": "foocafébaz"}, self.client_auto_encrypted) # Use clientEncryption.encrypt() to encrypt the string "cafe". diff --git a/test/test_examples.py b/test/test_examples.py index b97e1f7bfa..ea7229fb70 100644 --- a/test/test_examples.py +++ b/test/test_examples.py @@ -1111,7 +1111,7 @@ def update_employee_info(session): with client.start_session() as session: try: run_transaction_with_retry(update_employee_info, session) - except Exception: + except Exception: # noqa: TRY203 # Do something with error. raise diff --git a/test/test_fuzz_capture.py b/test/test_fuzz_capture.py new file mode 100644 index 0000000000..b7fcb57567 --- /dev/null +++ b/test/test_fuzz_capture.py @@ -0,0 +1,152 @@ +"""Tests for fuzz/capture_corpus.py (PYTHON-6178).""" + +from __future__ import annotations + +import sys +from hashlib import sha256 +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).parent.parent / "fuzz")) + +import capture_corpus + + +def write_unit(directory: Path, data: bytes) -> Path: + """Write a unit named by its content digest, like libFuzzer does.""" + path = directory / sha256(data).hexdigest() + path.write_bytes(data) + return path + + +@pytest.fixture +def dirs(tmp_path: Path) -> dict[str, Path]: + corpus = tmp_path / "corpus" + corpus.mkdir() + return { + "corpus": corpus, + "baseline": tmp_path / "baseline.txt", + "existing": tmp_path / "committed", + "out": tmp_path / "capture", + "summary": tmp_path / "summary.md", + } + + +def capture(dirs: dict[str, Path], max_units: int = 50, max_unit_bytes: int = 65536) -> int: + return capture_corpus.run( + corpus_dir=dirs["corpus"], + baseline=dirs["baseline"], + existing=dirs["existing"], + out=dirs["out"], + summary=dirs["summary"], + max_units=max_units, + max_unit_bytes=max_unit_bytes, + ) + + +def test_captures_new_units(dirs: dict[str, Path]) -> None: + write_unit(dirs["corpus"], b"new-unit") + + count = capture(dirs) + + assert count == 1 + captured = list(dirs["out"].iterdir()) + assert [p.name for p in captured] == [sha256(b"new-unit").hexdigest()] + assert captured[0].read_bytes() == b"new-unit" + + +def test_skips_baseline_units(dirs: dict[str, Path]) -> None: + write_unit(dirs["corpus"], b"seeded") + dirs["baseline"].write_text(sha256(b"seeded").hexdigest() + "\n") + + assert capture(dirs) == 0 + assert list(dirs["out"].iterdir()) == [] + + +def test_skips_committed_units(dirs: dict[str, Path]) -> None: + dirs["existing"].mkdir() + write_unit(dirs["existing"], b"already-committed") + write_unit(dirs["corpus"], b"already-committed") + + assert capture(dirs) == 0 + + +def test_skips_oversize_units(dirs: dict[str, Path]) -> None: + write_unit(dirs["corpus"], b"x" * 100) + write_unit(dirs["corpus"], b"y" * 50) + + assert capture(dirs, max_unit_bytes=99) == 1 + assert len(list(dirs["out"].iterdir())) == 1 + assert "per-unit cap" in dirs["summary"].read_text() + + +def test_per_run_cap_prefers_smallest(dirs: dict[str, Path]) -> None: + write_unit(dirs["corpus"], b"a" * 30) + write_unit(dirs["corpus"], b"b" * 10) + write_unit(dirs["corpus"], b"c" * 20) + + assert capture(dirs, max_units=2) == 2 + assert {p.read_bytes() for p in dirs["out"].iterdir()} == {b"b" * 10, b"c" * 20} + assert "per-run cap (2)" in dirs["summary"].read_text() + + +def test_dedups_identical_candidates_within_run(dirs: dict[str, Path]) -> None: + """Same contents under two names count once against the cap. + + libFuzzer digest-names corpus files, so the second name simulates a + crash artifact. + """ + dup = b"same" * 4 + distinct = b"distinct-unit-input" + write_unit(dirs["corpus"], dup) + (dirs["corpus"] / f"crash-{sha256(dup).hexdigest()[:8]}").write_bytes(dup) + write_unit(dirs["corpus"], distinct) + + assert capture(dirs, max_units=2) == 2 + assert {p.read_bytes() for p in dirs["out"].iterdir()} == {dup, distinct} + assert "Units dropped over the per-run cap (2): 0" in dirs["summary"].read_text() + + +def test_no_new_units_writes_summary_and_empty_out(dirs: dict[str, Path]) -> None: + assert capture(dirs) == 0 + assert list(dirs["out"].iterdir()) == [] + assert dirs["summary"].is_file() + + +def test_rejects_nonpositive_max_units(monkeypatch, capsys, dirs: dict[str, Path]) -> None: + """A cap of 0 or fewer is operator error; fail with an actionable message.""" + monkeypatch.setenv("FUZZ_CORPUS_MAX_UNITS", "0") + _argv(monkeypatch, dirs) + with pytest.raises(SystemExit): + capture_corpus.main() + assert "--max-units must be at least 1" in capsys.readouterr().err + + +def test_rejects_nonpositive_max_unit_bytes(monkeypatch, capsys, dirs: dict[str, Path]) -> None: + monkeypatch.setenv("FUZZ_CORPUS_MAX_UNIT_BYTES", "-1") + _argv(monkeypatch, dirs) + with pytest.raises(SystemExit): + capture_corpus.main() + assert "--max-unit-bytes must be at least 1" in capsys.readouterr().err + + +def _argv(monkeypatch, dirs: dict[str, Path]) -> None: + """Point main()'s argparse at the fixture directories.""" + monkeypatch.setattr( + sys, + "argv", + [ + "capture_corpus.py", + "--corpus-dir", + str(dirs["corpus"]), + "--baseline", + str(dirs["baseline"]), + "--existing", + str(dirs["existing"]), + "--out", + str(dirs["out"]), + "--summary", + str(dirs["summary"]), + ], + ) diff --git a/test/test_grid_file.py b/test/test_grid_file.py index 21c2c29d74..c83166cc77 100644 --- a/test/test_grid_file.py +++ b/test/test_grid_file.py @@ -23,7 +23,6 @@ import zipfile from io import BytesIO -from pymongo.synchronous.database import Database from test import ( IntegrationTest, UnitTest, @@ -34,6 +33,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.objectid import ObjectId from gridfs.errors import NoFile from gridfs.synchronous.grid_file import ( @@ -51,6 +52,9 @@ from pymongo.synchronous.helpers import iter, next from test.utils_shared import OvertCommandListener +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + _IS_SYNC = True diff --git a/test/test_gridfs.py b/test/test_gridfs.py index ab6a8f969a..6371fd2019 100644 --- a/test/test_gridfs.py +++ b/test/test_gridfs.py @@ -29,6 +29,8 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + import gridfs from bson.binary import Binary from gridfs.errors import CorruptGridFile, FileExists, NoFile @@ -39,12 +41,14 @@ ServerSelectionTimeoutError, ) from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.database import Database from pymongo.synchronous.mongo_client import MongoClient from test import IntegrationTest, client_context, unittest from test.utils import joinall from test.utils_shared import one +if TYPE_CHECKING: + from pymongo.synchronous.database import Database + _IS_SYNC = True diff --git a/test/test_heartbeat_monitoring.py b/test/test_heartbeat_monitoring.py index 1c0d45f46d..74e01392df 100644 --- a/test/test_heartbeat_monitoring.py +++ b/test/test_heartbeat_monitoring.py @@ -59,7 +59,7 @@ def _check_with_socket(self, *args, **kwargs): wait_until(lambda: len(listener.events) >= expected_len, "publish all events") # zip gives us len(expected_results) pairs. - for expected, actual in zip(expected_results, listener.events): + for expected, actual in zip(expected_results, listener.events, strict=False): self.assertEqual(expected, actual.__class__.__name__) self.assertEqual(actual.connection_id, responses[0]) if expected != "ServerHeartbeatStartedEvent": diff --git a/test/test_index_management.py b/test/test_index_management.py index 904c3fe665..74bb0b6ed5 100644 --- a/test/test_index_management.py +++ b/test/test_index_management.py @@ -21,8 +21,7 @@ import sys import time import uuid -from collections.abc import Mapping -from typing import Any +from typing import TYPE_CHECKING, Any import pytest @@ -38,6 +37,9 @@ from test.unified_format import generate_test_classes, get_test_path from test.utils_shared import AllowListEventListener, OvertCommandListener +if TYPE_CHECKING: + from collections.abc import Mapping + _IS_SYNC = True pytestmark = pytest.mark.search_index @@ -180,7 +182,6 @@ class TestSearchIndexProse(SearchIndexIntegrationBase): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_1(self): """Driver can successfully create and list search indexes.""" - # Create a new search index on ``self.coll0`` with the ``createSearchIndex`` helper. Use the following definition: model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = self.coll0.create_search_index(model) @@ -200,7 +201,6 @@ def test_case_1(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_2(self): """Driver can successfully create multiple indexes in batch.""" - # Create two new search indexes on ``self.coll0`` with the ``createSearchIndexes`` helper. name1 = "test-search-index-1" name2 = "test-search-index-2" @@ -235,7 +235,6 @@ def test_case_2(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_3(self): """Driver can successfully drop search indexes.""" - # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = self.coll0.create_search_index(model) @@ -254,7 +253,6 @@ def test_case_3(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_4(self): """Driver can update a search index.""" - # Create a new search index on ``self.coll0``. model = {"name": _NAME, "definition": {"mappings": {"dynamic": False}}} resp = self.coll0.create_search_index(model) @@ -295,7 +293,6 @@ def test_case_5(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_6(self): """Driver can successfully create and list search indexes with non-default readConcern and writeConcern.""" - # Apply a write concern ``WriteConcern(w=1)`` and a read concern with ``ReadConcern(level="majority")`` to ``self.coll0``. coll0 = self.coll0.with_options( write_concern=WriteConcern(w="1"), read_concern=ReadConcern(level="majority") @@ -321,7 +318,6 @@ def test_case_6(self): @flaky(reason="PYTHON-6056", affects_cpython_linux=True) def test_case_7(self): """Driver handles index types.""" - # Use these search and vector search definitions for indexes. search_definition = {"mappings": {"dynamic": False}} vector_search_definition = { diff --git a/test/test_json_util.py b/test/test_json_util.py index ada04955c4..fadcb431f6 100644 --- a/test/test_json_util.py +++ b/test/test_json_util.py @@ -343,7 +343,7 @@ def test_regex_object_hook(self): loaded = json_util.object_hook(json.loads(json_re)) self.assertIsInstance(loaded, Regex) self.assertEqual(pat, loaded.pattern) - self.assertEqual(re.U, loaded.flags) + self.assertEqual(re.UNICODE, loaded.flags) def test_regex(self): for regex_instance in (re.compile("a*b", re.IGNORECASE), Regex("a*b", re.IGNORECASE)): @@ -354,7 +354,7 @@ def test_regex(self): self.assertEqual("a*b", res.pattern) self.assertEqual(re.IGNORECASE, res.flags) - unicode_options = re.I | re.M | re.S | re.U | re.X + unicode_options = re.IGNORECASE | re.MULTILINE | re.DOTALL | re.UNICODE | re.VERBOSE regex = re.compile("a*b", unicode_options) res = self.round_tripped({"r": regex})["r"] self.assertEqual(unicode_options, res.flags) @@ -370,17 +370,19 @@ def test_regex(self): # Check order. self.assertEqual( '{"$regularExpression": {"pattern": ".*", "options": "mx"}}', - json_util.dumps(Regex(".*", re.M | re.X)), + json_util.dumps(Regex(".*", re.MULTILINE | re.VERBOSE)), ) self.assertEqual( '{"$regularExpression": {"pattern": ".*", "options": "mx"}}', - json_util.dumps(re.compile(b".*", re.M | re.X)), + json_util.dumps(re.compile(b".*", re.MULTILINE | re.VERBOSE)), ) self.assertEqual( '{"$regex": ".*", "$options": "mx"}', - json_util.dumps(Regex(".*", re.M | re.X), json_options=LEGACY_JSON_OPTIONS), + json_util.dumps( + Regex(".*", re.MULTILINE | re.VERBOSE), json_options=LEGACY_JSON_OPTIONS + ), ) def test_regex_validation(self): diff --git a/test/test_json_util_integration.py b/test/test_json_util_integration.py index 5772309842..9277b12d99 100644 --- a/test/test_json_util_integration.py +++ b/test/test_json_util_integration.py @@ -1,12 +1,14 @@ from __future__ import annotations -from collections.abc import MutableMapping -from typing import Any +from typing import TYPE_CHECKING, Any from bson import Binary, Code, DBRef, ObjectId, json_util from bson.binary import USER_DEFINED_SUBTYPE from test import IntegrationTest +if TYPE_CHECKING: + from collections.abc import MutableMapping + _IS_SYNC = True diff --git a/test/test_kms_connect.py b/test/test_kms_connect.py index f5e79b5048..084cfae266 100644 --- a/test/test_kms_connect.py +++ b/test/test_kms_connect.py @@ -37,10 +37,9 @@ import threading import time from asyncio.trsock import TransportSocket -from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager -from typing import Any +from typing import TYPE_CHECKING, Any from unittest import mock import pytest @@ -59,6 +58,9 @@ from pymongo.ssl_support import get_ssl_context from test.helpers_shared import CA_PEM, CERT_PATH, CLIENT_PEM +if TYPE_CHECKING: + from collections.abc import Callable + pytestmark = [pytest.mark.encryption, pytest.mark.asyncio] _KMS_ADDRESS = ("kms.example.com", 443) @@ -839,7 +841,7 @@ def blocker(): task = asyncio.create_task(callback(_kms_context(timeout=1.0))) await asyncio.sleep(0.2) # Let the coroutine queue its connect. assert not task.done(), "connect finished before the deadline" - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await task elapsed = time.monotonic() - start assert elapsed < 2.5, f"the wait outlived the deadline: {elapsed:.1f}s" @@ -928,7 +930,7 @@ async def raced_wait_for(awaitable, timeout=None): with mock.patch.object(HTTPProxyKMSConnect, "_tunnel", spy_tunnel): with mock.patch("asyncio.wait_for", raced_wait_for): callback = api.proxy(f"https://{host}:{port}", _insecure_client_context()) - with pytest.raises(socket.timeout, match="timed out connecting through the proxy"): + with pytest.raises(TimeoutError, match="timed out connecting through the proxy"): await callback(_kms_context()) assert len(tunneled) == 1 @@ -937,12 +939,11 @@ async def raced_wait_for(awaitable, timeout=None): @both_apis async def test_connect_timeout_is_not_reclassified(api): - # A timed-out connect keeps its socket.timeout type. def timeout_connect(self, address): - raise socket.timeout("timed out") + raise TimeoutError("timed out") with mock.patch.object(socket.socket, "connect", timeout_connect): - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): HTTPProxyKMSConnect("http://127.0.0.1:9999")._connect_proxy(time.monotonic() + 10) @@ -991,7 +992,7 @@ async def test_remaining_raises_once_the_deadline_passes(api): from pymongo._kms_connect_shared import _remaining assert _remaining(time.monotonic() + 5) > 0 - with pytest.raises(socket.timeout): + with pytest.raises(TimeoutError): _remaining(time.monotonic() - 1) diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index 66a410a5f1..56c92d9330 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -181,7 +181,7 @@ def lock_pool(self): # Wait for the unlock flag. unlock_pool = self.wait(self.unlock, 10) if not unlock_pool: - raise Exception("timed out waiting for unlock signal: deadlock?") + raise TimeoutError("timed out waiting for unlock signal: deadlock?") def wait(self, event: Event, timeout: int): if _IS_SYNC: @@ -189,7 +189,7 @@ def wait(self, event: Event, timeout: int): else: try: asyncio.wait_for(event.wait(), timeout=timeout) - except asyncio.TimeoutError: + except TimeoutError: return False return True diff --git a/test/test_monitor.py b/test/test_monitor.py index 51730d8579..b19b64715c 100644 --- a/test/test_monitor.py +++ b/test/test_monitor.py @@ -106,7 +106,8 @@ def test_cleanup_executors_on_client_close(self): @client_context.require_sync def test_no_thread_start_runtime_err_on_shutdown(self): """Test we silence noisy runtime errors fired when the MongoClient spawns a new thread - on process shutdown.""" + on process shutdown. + """ command = [ sys.executable, "-c", diff --git a/test/test_monitoring.py b/test/test_monitoring.py index 4b28687f4b..1611666a8c 100644 --- a/test/test_monitoring.py +++ b/test/test_monitoring.py @@ -833,7 +833,7 @@ def test_insert_many(self): count = 0 operation_id = started[0].operation_id self.assertIsInstance(operation_id, int) - for start, succeed in zip(started, succeeded): + for start, succeed in zip(started, succeeded, strict=True): self.assertIsInstance(start, monitoring.CommandStartedEvent) cmd = sanitize_cmd(start.command) self.assertEqual(["insert", "ordered", "documents"], list(cmd.keys())) @@ -873,7 +873,7 @@ def test_insert_many_unacknowledged(self): documents = [] operation_id = started[0].operation_id self.assertIsInstance(operation_id, int) - for start, succeed in zip(started, succeeded): + for start, succeed in zip(started, succeeded, strict=True): self.assertIsInstance(start, monitoring.CommandStartedEvent) cmd = sanitize_cmd(start.command) cmd.pop("writeConcern", None) @@ -916,7 +916,7 @@ def test_bulk_write(self): succeeded = self.listener.succeeded_events self.assertEqual(0, len(self.listener.failed_events)) operation_id = started[0].operation_id - pairs = list(zip(started, succeeded)) + pairs = list(zip(started, succeeded, strict=True)) self.assertEqual(3, len(pairs)) for start, succeed in pairs: self.assertIsInstance(start, monitoring.CommandStartedEvent) @@ -1032,7 +1032,7 @@ def test_write_errors(self): succeeded = self.listener.succeeded_events self.assertEqual(0, len(self.listener.failed_events)) operation_id = started[0].operation_id - pairs = list(zip(started, succeeded)) + pairs = list(zip(started, succeeded, strict=True)) errors = [] for start, succeed in pairs: self.assertIsInstance(start, monitoring.CommandStartedEvent) diff --git a/test/test_ocsp_support.py b/test/test_ocsp_support.py index 294688a4a3..021507411e 100644 --- a/test/test_ocsp_support.py +++ b/test/test_ocsp_support.py @@ -281,7 +281,7 @@ def test_by_name_match(self): cert2.subject = "other" cert2.issuer = "issuer" - result = _get_certs_by_name([cert1, cert2], issuer, cast(Name, "responder")) + result = _get_certs_by_name([cert1, cert2], issuer, cast("Name", "responder")) self.assertEqual(result, [cert1]) def test_by_name_no_match(self): @@ -291,7 +291,7 @@ def test_by_name_no_match(self): cert.subject = "other" cert.issuer = "issuer" - result = _get_certs_by_name([cert], issuer, cast(Name, "responder")) + result = _get_certs_by_name([cert], issuer, cast("Name", "responder")) self.assertEqual(result, []) diff --git a/test/test_periodic_executor.py b/test/test_periodic_executor.py index d564042c30..9523ceaeda 100644 --- a/test/test_periodic_executor.py +++ b/test/test_periodic_executor.py @@ -23,7 +23,7 @@ import textwrap import threading import time -from typing import Any +from typing import Any, Optional from unittest import mock _interpreters: Any = None @@ -155,6 +155,91 @@ def target(): executor.join(timeout=2) self.assertGreaterEqual(called, 2) + def test_close_from_own_task_does_not_cancel(self): + # Closing the executor from its own task must not cancel it + # (PYTHON-6226). + runs = 0 + + def target(): + nonlocal runs + executor.close() + # Raises CancelledError here if close() cancelled this task. + runs += 1 + return False + + executor = self._make_executor(target=target) + executor.open() + executor.join(timeout=2) + self.assertEqual(runs, 1, "target did not finish after close() from its own task") + if not _IS_SYNC: + assert executor._task is not None + self.assertFalse(executor._task.cancelled(), "executor task cancelled itself") + # The executor can be restarted after a self-close. + executor.open() + executor.join(timeout=2) + self.assertEqual(runs, 2, "executor did not restart after a self-close") + + def test_close_from_thread_without_event_loop(self): + # close() can run off the event loop as a weakref callback, where + # asyncio.current_task() raises RuntimeError. + if _IS_SYNC: + started = threading.Event() + else: + started = asyncio.Event() + + def target(): + started.set() + return True + + executor = self._make_executor(min_interval=0.5, target=target) + executor.open() + if _IS_SYNC: + started.wait(timeout=2) + else: + assert isinstance(started, asyncio.Event) + asyncio.wait_for(started.wait(), timeout=2) + + close_error: BaseException | None = None + + def close_off_loop(): + nonlocal close_error + try: + executor.close() + except BaseException as exc: + close_error = exc + + real_task: Any = None + mock_task: Any = None + if not _IS_SYNC: + # Cancel a mock off the loop: cancelling the real task from + # another thread is not thread-safe under asyncio debug mode. + assert executor._task is not None + real_task = executor._task + mock_task = mock.MagicMock() + mock_task.cancelling.return_value = 0 + executor._task = mock_task + try: + thread = threading.Thread(target=close_off_loop) + thread.start() + if _IS_SYNC: + thread.join(timeout=2) + else: + # Do not block the event loop while joining the thread. + asyncio.to_thread(thread.join, 2) + finally: + if not _IS_SYNC: + executor._task = real_task + self.assertIsNone(close_error, "close() raised from a thread without a running event loop") + if not _IS_SYNC: + assert mock_task is not None and real_task is not None + mock_task.cancel.assert_called_once() + # Cancel the real executor on the event loop thread. + real_task.cancel() + executor.join(timeout=2) + self.assertTrue(executor._stopped) + if not _IS_SYNC: + self.assertTrue(real_task.cancelled()) + def test_target_exception_stops_executor(self): call_count = 0 diff --git a/test/test_raw_bson_shared.py b/test/test_raw_bson_shared.py index b7d54879aa..0cbf560d09 100644 --- a/test/test_raw_bson_shared.py +++ b/test/test_raw_bson_shared.py @@ -43,7 +43,8 @@ class _TaggedRawBSONDocument(RawBSONDocument): """RawBSONDocument subclass with a different __init__ signature and - extra instance state, stored in __dict__.""" + extra instance state, stored in __dict__. + """ def __init__(self, bson_bytes, tag, codec_options=None): super().__init__(bson_bytes, codec_options) @@ -303,7 +304,7 @@ def test_preserve_key_ordering(self): ] rawdoc = RawBSONDocument(encode(SON(keyvaluepairs))) - for rkey, elt in zip(rawdoc, keyvaluepairs): + for rkey, elt in zip(rawdoc, keyvaluepairs, strict=True): self.assertEqual(rkey, elt[0]) def test_contains_code_with_scope(self): diff --git a/test/test_read_preferences.py b/test/test_read_preferences.py index 2cd2f1b061..fdd1bd9f8b 100644 --- a/test/test_read_preferences.py +++ b/test/test_read_preferences.py @@ -241,7 +241,7 @@ def test_zero_latency(self): # Generate unique ping times. while len(ping_times) < len(self.client.nodes): ping_times.add(random.random()) - for ping_time, host in zip(ping_times, self.client.nodes): + for ping_time, host in zip(ping_times, self.client.nodes, strict=True): ServerDescription._host_to_round_trip_time[host] = ping_time try: client = connected(self.rs_client(readPreference="nearest", localThresholdMS=0)) @@ -558,7 +558,7 @@ def test_read_preference_hedge_deprecated(self): "secondaryPreferred": SecondaryPreferred, "nearest": Nearest, } - for _, cls in cases.items(): + for cls in cases.values(): with self.assertRaises(DeprecationWarning): cls(hedge={"enabled": True}) @@ -573,7 +573,7 @@ def test_send_hedge(self): listener = OvertCommandListener() client = self.rs_client(event_listeners=[listener]) client.admin.command("ping") - for _mode, cls in cases.items(): + for cls in cases.values(): with _ignore_deprecations(): pref = cls(hedge={"enabled": True}) coll = client.test.get_collection("coll", read_preference=pref) diff --git a/test/test_retryable_writes.py b/test/test_retryable_writes.py index d64af51bf0..f523d9d03a 100644 --- a/test/test_retryable_writes.py +++ b/test/test_retryable_writes.py @@ -365,6 +365,9 @@ def test_batch_splitting_retry_fails(self): self.assertEqual(final_txn, expected_txn) self.assertEqual(coll.find_one(projection={"_id": True}), {"_id": 1}) + # loadBalanced=true clients cannot use multiple seeds, and a retry routed to + # a different mongos is not observable through a load balancer (PYTHON-6262). + @client_context.require_no_load_balancer @client_context.require_multiple_mongoses @client_context.require_failCommand_fail_point def test_retryable_writes_in_sharded_cluster_multiple_available(self): diff --git a/test/test_sdam_monitoring_spec.py b/test/test_sdam_monitoring_spec.py index 6e63f94ea3..ebdb9fa82d 100644 --- a/test/test_sdam_monitoring_spec.py +++ b/test/test_sdam_monitoring_spec.py @@ -25,13 +25,14 @@ sys.path[0:0] = [""] +from typing import TYPE_CHECKING + from bson.json_util import object_hook from pymongo import MongoClient, monitoring from pymongo.common import clean_node from pymongo.errors import ConnectionFailure, NotPrimaryError from pymongo.hello import Hello from pymongo.server_description import ServerDescription -from pymongo.synchronous.collection import Collection from pymongo.synchronous.monitor import Monitor from pymongo.topology_description import TOPOLOGY_TYPE from test import IntegrationTest, client_context, client_knobs, unittest @@ -41,6 +42,9 @@ wait_until, ) +if TYPE_CHECKING: + from pymongo.synchronous.collection import Collection + _IS_SYNC = True # Location of JSON test specifications. @@ -67,7 +71,7 @@ def compare_topology_descriptions(expected, actual): if len(expected) != len(actual): return False for exp_server in expected: - for _address, actual_server in actual.items(): + for actual_server in actual.values(): if compare_server_descriptions(exp_server, actual_server): break else: diff --git a/test/test_server_selection.py b/test/test_server_selection.py index d877392aaf..5f4c6d1a6d 100644 --- a/test/test_server_selection.py +++ b/test/test_server_selection.py @@ -118,7 +118,7 @@ def all_hosts_started(): def test_invalid_server_selector(self): # Client initialization must fail if server_selector is not callable. for selector_candidate in [[], 10, "string", {}]: - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): MongoClient(connect=False, server_selector=selector_candidate) # None value for server_selector is OK. diff --git a/test/test_session.py b/test/test_session.py index 6cd28d27fe..3b48acc8de 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -19,10 +19,9 @@ import copy import sys import time -from collections.abc import Callable from inspect import iscoroutinefunction from io import BytesIO -from typing import Any +from typing import TYPE_CHECKING, Any from test.helpers import ExceptionCatchingTask @@ -53,6 +52,9 @@ wait_until, ) +if TYPE_CHECKING: + from collections.abc import Callable + _IS_SYNC = True @@ -1019,7 +1021,7 @@ def test_core(self): self.assertIsNone(sess2.cluster_time) self.assertIsNone(sess2.operation_time) self.assertRaises(TypeError, sess2.advance_cluster_time, 1) - self.assertRaises(ValueError, sess2.advance_cluster_time, {}) + self.assertRaises(TypeError, sess2.advance_cluster_time, {}) self.assertRaises(TypeError, sess2.advance_operation_time, 1) # No error assert sess.cluster_time is not None diff --git a/test/test_sfp.py b/test/test_sfp.py index b5dcfa5cc7..aac644e02a 100644 --- a/test/test_sfp.py +++ b/test/test_sfp.py @@ -19,7 +19,7 @@ import os import sys import unittest -from typing import Any +from typing import TYPE_CHECKING, Any import pytest @@ -27,9 +27,11 @@ from bson import ObjectId from pymongo.server_api import ServerApi -from pymongo.synchronous.mongo_client import MongoClient from test import PyMongoTestCase +if TYPE_CHECKING: + from pymongo.synchronous.mongo_client import MongoClient + _IS_SYNC = True pytestmark = pytest.mark.sfp @@ -46,7 +48,7 @@ def _require_env(name: str) -> str: value = os.environ.get(name) if not value: - raise Exception(f"Must set {name} env variable to test.") + raise ValueError(f"Must set {name} env variable to test.") return value diff --git a/test/test_ssl.py b/test/test_ssl.py index cc1b900eeb..66f285abf3 100644 --- a/test/test_ssl.py +++ b/test/test_ssl.py @@ -147,7 +147,6 @@ def test_ssl_session_cache(self): @unittest.skipUnless(_IS_SYNC, "Tests sync wrap_socket path only") def test_tls_session_reused_on_second_connection(self): """Cached TLS session is passed to wrap_socket on subsequent connections.""" - fake_session = object() cache: list = [fake_session] diff --git a/test/test_topology.py b/test/test_topology.py index a767b4fa24..0dd0f90f78 100644 --- a/test/test_topology.py +++ b/test/test_topology.py @@ -26,12 +26,12 @@ from pymongo import common from pymongo.errors import AutoReconnect, ConfigurationError, ConnectionFailure from pymongo.hello import Hello, HelloCompat +from pymongo.pool_options import PoolOptions from pymongo.read_preferences import Primary, ReadPreference, Secondary from pymongo.server_description import ServerDescription from pymongo.server_selectors import any_server_selector, writable_server_selector from pymongo.server_type import SERVER_TYPE from pymongo.synchronous.monitor import Monitor -from pymongo.synchronous.pool import PoolOptions from pymongo.synchronous.server import Server from pymongo.synchronous.settings import TopologySettings from pymongo.synchronous.topology import Topology diff --git a/test/test_typing.py b/test/test_typing.py index 945442d4a9..85b5d9bc1f 100644 --- a/test/test_typing.py +++ b/test/test_typing.py @@ -27,17 +27,17 @@ TYPE_CHECKING, Any, TypeVar, - Union, cast, ) if TYPE_CHECKING: from typing import NotRequired - from typing_extensions import TypedDict + from typing_extensions import TypedDict # noqa: TC004 - from bson import Binary, ObjectId - from bson.binary import BinaryVector, BinaryVectorDtype + from bson import Binary, ObjectId # noqa: TC004 + from bson.binary import BinaryVector, BinaryVectorDtype # noqa: TC004 + from pymongo.synchronous.collection import Collection class Movie(TypedDict): name: str @@ -71,7 +71,6 @@ class ImplicitMovie(TypedDict): from pymongo import ASCENDING, MongoClient from pymongo.operations import DeleteOne, InsertOne, ReplaceOne from pymongo.read_preferences import ReadPreference -from pymongo.synchronous.collection import Collection from pymongo.synchronous.cursor import Cursor from test import IntegrationTest, PyMongoTestCase, client_context @@ -93,7 +92,7 @@ def inner(*args, **kwargs): raise unittest.SkipTest("Used for Type Checking Only") func(*args, **kwargs) - return cast(FuncT, inner) + return cast("FuncT", inner) class TestMypyFails(unittest.TestCase): @@ -157,12 +156,12 @@ def test_distinct(self) -> None: def collection_distinct( collection: Collection, - ) -> list[None | int | str | ObjectId | bool]: + ) -> list[int | str | ObjectId | bool | None]: return collection.distinct("_id") def cursor_distinct( collection: Collection, - ) -> list[None | int | str | ObjectId | bool]: + ) -> list[int | str | ObjectId | bool | None]: cursor = collection.find() return cursor.distinct("_id") @@ -175,26 +174,24 @@ def test_bulk_write(self) -> None: coll: Collection[Movie] = self.coll requests: list[InsertOne[Movie]] = [InsertOne(Movie(name="American Graffiti", year=1973))] self.assertTrue(coll.bulk_write(requests).acknowledged) - new_requests: list[Union[InsertOne[Movie], ReplaceOne[Movie]]] = [] - input_list: list[Union[InsertOne[Movie], ReplaceOne[Movie]]] = [ + input_list: list[InsertOne[Movie] | ReplaceOne[Movie]] = [ InsertOne(Movie(name="American Graffiti", year=1973)), ReplaceOne({}, Movie(name="American Graffiti", year=1973)), ] - for i in input_list: - new_requests.append(i) + new_requests: list[InsertOne[Movie] | ReplaceOne[Movie]] = list.copy(input_list) self.assertTrue(coll.bulk_write(new_requests).acknowledged) # Because ReplaceOne is not generic, type checking is not enforced for ReplaceOne in the first example. @only_type_check def test_bulk_write_heterogeneous(self): coll: Collection[Movie] = self.coll - requests: list[Union[InsertOne[Movie], ReplaceOne, DeleteOne]] = [ + requests: list[InsertOne[Movie] | ReplaceOne | DeleteOne] = [ InsertOne(Movie(name="American Graffiti", year=1973)), ReplaceOne({}, {"name": "American Graffiti", "year": "WRONG_TYPE"}), DeleteOne({}), ] self.assertTrue(coll.bulk_write(requests).acknowledged) - requests_two: list[Union[InsertOne[Movie], ReplaceOne[Movie], DeleteOne]] = [ + requests_two: list[InsertOne[Movie] | ReplaceOne[Movie] | DeleteOne] = [ InsertOne(Movie(name="American Graffiti", year=1973)), ReplaceOne( {}, diff --git a/test/test_uri_spec.py b/test/test_uri_spec.py index c44d57ab8c..7aa8803abb 100644 --- a/test/test_uri_spec.py +++ b/test/test_uri_spec.py @@ -135,7 +135,7 @@ def run_scenario(self): "Incorrect number of hosts parsed from URI", ) - for exp, actual in zip(test["hosts"], options["nodelist"]): + for exp, actual in zip(test["hosts"], options["nodelist"], strict=True): self.assertEqual( exp["host"], actual[0], diff --git a/test/transactions/unified/error-labels-blockConnection.json b/test/transactions/unified/error-labels-blockConnection.json index 8da04d1005..60d753edce 100644 --- a/test/transactions/unified/error-labels-blockConnection.json +++ b/test/transactions/unified/error-labels-blockConnection.json @@ -12,6 +12,12 @@ } ], "createEntities": [ + { + "client": { + "id": "failPointClient", + "useMultipleMongoses": false + } + }, { "client": { "id": "client0", @@ -60,7 +66,7 @@ "object": "testRunner", "name": "failPoint", "arguments": { - "client": "client0", + "client": "failPointClient", "failPoint": { "configureFailPoint": "failCommand", "mode": { diff --git a/test/unified_format.py b/test/unified_format.py index 2ebf7c201b..809b92b258 100644 --- a/test/unified_format.py +++ b/test/unified_format.py @@ -31,17 +31,15 @@ import time import traceback from collections import defaultdict -from collections.abc import Mapping from inspect import iscoroutinefunction from pathlib import Path -from typing import Any, Optional +from typing import TYPE_CHECKING, Any, Optional import pytest import pymongo from bson import SON, json_util from bson.codec_options import DEFAULT_CODEC_OPTIONS -from bson.objectid import ObjectId from gridfs import GridFSBucket, GridOut, NoFile from gridfs.errors import CorruptGridFile from pymongo import ASCENDING, CursorType, MongoClient, _csot @@ -79,7 +77,6 @@ from pymongo.synchronous.encryption import ClientEncryption from pymongo.synchronous.helpers import next from pymongo.topology_description import TopologyDescription -from pymongo.typings import _Address from pymongo.write_concern import WriteConcern from test import ( IntegrationTest, @@ -112,6 +109,12 @@ from test.utils_spec_runner import SpecRunnerThread from test.version import Version +if TYPE_CHECKING: + from collections.abc import Mapping + + from bson.objectid import ObjectId + from pymongo.typings import _Address + _IS_SYNC = True IS_INTERRUPTED = False @@ -747,7 +750,9 @@ def process_error(self, exception, spec): ) actual_write_concern_errors = exception.details.get("writeConcernErrors", []) self.assertEqual(len(write_concern_errors), len(actual_write_concern_errors)) - for expected_wce, actual_wce in zip(write_concern_errors, actual_write_concern_errors): + for expected_wce, actual_wce in zip( + write_concern_errors, actual_write_concern_errors, strict=True + ): # Use the spec's WriteConcernError field names. formatted_actual_wce = { "code": actual_wce.get("code", ""), @@ -1162,10 +1167,9 @@ def _testOperation_assertSessionUnpinned(self, spec): self.assertIsNone(session._transaction.pinned_address) def __get_last_two_command_lsids(self, listener): - cmd_started_events = [] - for event in reversed(listener.events): - if isinstance(event, CommandStartedEvent): - cmd_started_events.append(event) + cmd_started_events = [ + event for event in reversed(listener.events) if isinstance(event, CommandStartedEvent) + ] if len(cmd_started_events) < 2: self.fail( "Needed 2 CommandStartedEvents to compare lsids, got %s" % (len(cmd_started_events)) @@ -1267,7 +1271,7 @@ def _testOperation_waitForPrimaryChange(self, spec: dict) -> None: old_description: TopologyDescription = self.entity_map[spec["priorTopologyDescription"]] timeout = spec["timeoutMS"] / 1000.0 - def get_primary(td: TopologyDescription) -> Optional[_Address]: + def get_primary(td: TopologyDescription) -> _Address | None: servers = writable_server_selector(Selection.from_topology_description(td)) if servers and servers[0].server_type == SERVER_TYPE.RSPrimary: return servers[0].address @@ -1453,7 +1457,7 @@ def format_logs(log_list): len(actual_logs), f"expected {client['messages']} but got {actual_logs}", ) - for expected_msg, actual_msg in zip(client["messages"], actual_logs): + for expected_msg, actual_msg in zip(client["messages"], actual_logs, strict=True): expected_data, actual_data = expected_msg.pop("data"), actual_msg.pop("data") if "failureIsRedacted" in expected_msg: diff --git a/test/unified_format_shared.py b/test/unified_format_shared.py index 8a0a3cd46b..7e5595baac 100644 --- a/test/unified_format_shared.py +++ b/test/unified_format_shared.py @@ -26,8 +26,7 @@ import time import types from collections import abc -from collections.abc import MutableMapping -from typing import Any, Union +from typing import TYPE_CHECKING, Any from bson import ( RE_TYPE, @@ -79,8 +78,6 @@ _ServerHeartbeatEvent, ) from pymongo.results import BulkWriteResult -from pymongo.server_description import ServerDescription -from pymongo.topology_description import TopologyDescription from test.helpers_shared import ( AWS_CREDS, AWS_CREDS_2, @@ -94,6 +91,12 @@ ) from test.utils_shared import CMAPListener, camel_to_snake, parse_collection_options +if TYPE_CHECKING: + from collections.abc import MutableMapping + + from pymongo.server_description import ServerDescription + from pymongo.topology_description import TopologyDescription + JSON_OPTS = json_util.JSONOptions(tz_aware=False) IS_INTERRUPTED = False @@ -336,18 +339,18 @@ def failed(self, event): else: self.add_event(event) - def opened(self, event: Union[ServerOpeningEvent, TopologyOpenedEvent]) -> None: + def opened(self, event: ServerOpeningEvent | TopologyOpenedEvent) -> None: self.add_event(event) def description_changed( - self, event: Union[ServerDescriptionChangedEvent, TopologyDescriptionChangedEvent] + self, event: ServerDescriptionChangedEvent | TopologyDescriptionChangedEvent ) -> None: self.add_event(event) def topology_changed(self, event: TopologyDescriptionChangedEvent) -> None: self.add_event(event) - def closed(self, event: Union[ServerClosedEvent, TopologyClosedEvent]) -> None: + def closed(self, event: ServerClosedEvent | TopologyClosedEvent) -> None: self.add_event(event) @@ -538,7 +541,7 @@ def match_result(self, expectation, actual, in_recursive_call=False, test=True): if isinstance(expectation, abc.MutableSequence): self.test.assertIsInstance(actual, abc.MutableSequence) - for e, a in zip(expectation, actual): + for e, a in zip(expectation, actual, strict=False): if isinstance(e, abc.Mapping): res = self._match_document(e, a, is_root=not in_recursive_call, test=test) else: @@ -665,7 +668,7 @@ def match_event(self, expectation, actual): elif name == "topologyClosedEvent": self.test.assertIsInstance(actual, TopologyClosedEvent) else: - raise Exception(f"Unsupported event type {name}") + raise ValueError(f"Unsupported event type {name}") self.match_event_fields(actual, spec) diff --git a/test/utils.py b/test/utils.py index e52fd336e2..53d8e9dd95 100644 --- a/test/utils.py +++ b/test/utils.py @@ -27,9 +27,9 @@ import unittest from functools import wraps from inspect import iscoroutinefunction +from typing import TYPE_CHECKING from bson.son import SON -from pymongo import MongoClient from pymongo.errors import ConfigurationError from pymongo.hello import HelloCompat from pymongo.lock import _create_lock @@ -37,7 +37,10 @@ from pymongo.pool_shared import _CancellationContext, _PoolGeneration from pymongo.read_preferences import ReadPreference from pymongo.server_selectors import any_server_selector, writable_server_selector -from pymongo.synchronous.pool import Pool + +if TYPE_CHECKING: + from pymongo import MongoClient + from pymongo.synchronous.pool import Pool _IS_SYNC = True @@ -215,9 +218,9 @@ def wrapper(*args, **kwargs): passes += 1 if passes == min_passes: return result - except Exception as e: + except Exception: if i == max_runs - 1: - raise e + raise print( f"Retrying after attempt {i + 1} of {func_name or target_func.__name__} failed with ({reason})):\n" f"{traceback.format_exc()}", diff --git a/tools/ensure_future_annotations_import.py b/tools/ensure_future_annotations_import.py index e98e7ed04e..d3dfb781d6 100644 --- a/tools/ensure_future_annotations_import.py +++ b/tools/ensure_future_annotations_import.py @@ -27,7 +27,7 @@ continue found = False with open(path) as fid: - for line in fid.readlines(): + for line in fid: if line.strip() == pattern: found = True break diff --git a/tools/fail_if_no_c.py b/tools/fail_if_no_c.py index bb50081ad5..9f6ad21de5 100644 --- a/tools/fail_if_no_c.py +++ b/tools/fail_if_no_c.py @@ -36,11 +36,11 @@ def main() -> None: try: from pymongo import _cmessage # type:ignore[attr-defined] # noqa: F401 except Exception as e: - LOGGER.exception(e) + LOGGER.exception(e) # noqa: TRY401 try: from bson import _cbson # type:ignore[attr-defined] # noqa: F401 except Exception as e: - LOGGER.exception(e) + LOGGER.exception(e) # noqa: TRY401 sys.exit("could not load C extensions") diff --git a/tools/generate_sbom_requirements.py b/tools/generate_sbom_requirements.py index aa8d5579ca..ad6fa2cd48 100644 --- a/tools/generate_sbom_requirements.py +++ b/tools/generate_sbom_requirements.py @@ -23,14 +23,12 @@ def collect_files(root: Path) -> list[Path]: Returns: list[Path]: A list of Paths to requirement files to include in the SBOM. """ - files = [] - # requirements.txt + all requirements/**/*.txt - for p in [root / "requirements.txt", *root.glob("requirements/**/*.txt")]: - if p.is_file() and p.name not in EXCLUDED_NAMES: - files.append(p) - - return files + return [ + p + for p in [root / "requirements.txt", *root.glob("requirements/**/*.txt")] + if p.is_file() and p.name not in EXCLUDED_NAMES + ] def write_combined_req_files(root: Path, files: list[Path], outname: str) -> Path: diff --git a/tools/synchro.py b/tools/synchro.py index 4d2f865479..7cb68d4ca7 100644 --- a/tools/synchro.py +++ b/tools/synchro.py @@ -230,11 +230,11 @@ def apply_is_sync(lines: list[str], file: str) -> list[str]: index = lines.index(is_sync) is_sync = is_sync.replace("False", "True") lines[index] = is_sync - except StopIteration as e: + except StopIteration: print( f"Missing _IS_SYNC at top of async file {file.replace('synchronous', 'asynchronous')}" ) - raise e + raise return lines @@ -418,14 +418,15 @@ def main() -> None: for f in generated_files: print(f" {f}") - subprocess.run( # noqa: S603 - [sys.executable, "-m", "ruff", "check", *generated_files, "--fix", *ruff_extra], - check=is_ci, - ) - subprocess.run( # noqa: S603 - [sys.executable, "-m", "ruff", "format", *generated_files, *ruff_extra], - check=is_ci, - ) + if generated_files: + subprocess.run( # noqa: S603 + [sys.executable, "-m", "ruff", "check", *generated_files, "--fix", *ruff_extra], + check=is_ci, + ) + subprocess.run( # noqa: S603 + [sys.executable, "-m", "ruff", "format", *generated_files, *ruff_extra], + check=is_ci, + ) if is_ci and generated_files: result = subprocess.run( # noqa: S603 diff --git a/tools/test_synchro.py b/tools/test_synchro.py index 3f46f52044..e6a1cc3b8f 100644 --- a/tools/test_synchro.py +++ b/tools/test_synchro.py @@ -4,9 +4,11 @@ import sys from pathlib import Path +from typing import TYPE_CHECKING from unittest.mock import patch -import pytest +if TYPE_CHECKING: + import pytest sys.path.insert(0, str(Path(__file__).parent)) diff --git a/uv.lock b/uv.lock index 0b1489c36f..3736fc9132 100644 --- a/uv.lock +++ b/uv.lock @@ -1,15 +1,11 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.11.5'", "python_full_version < '3.11.5'", ] -[options] -exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. -exclude-newer-span = "P7D" - [[package]] name = "accessible-pygments" version = "0.0.5" @@ -33,21 +29,38 @@ wheels = [ [[package]] name = "anyio" -version = "4.15.1" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "idna" }, { name = "typing-extensions", marker = "python_full_version < '3.15'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, +] + +[[package]] +name = "atheris" +version = "3.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11.5'", +] +sdist = { url = "https://files.pythonhosted.org/packages/f8/58/5965955898e16bee17c8379eae12194993bf641c4629016991248b862069/atheris-3.0.0.tar.gz", hash = "sha256:1f0929c7bc3040f3fe4102e557718734190cf2d7718bbb8e3ce6d3eb56ef5bb3", size = 373239, upload-time = "2025-11-24T23:54:02.15Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/15/cf109e2e8696a54c8c4bc3ef79a79bec32361eceb64eaa36690a682e83a9/atheris-3.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8a5c8a781467c187da40fd29139784193e2647058831f837f675d0bb8cbd8746", size = 34805555, upload-time = "2025-11-24T23:53:53.477Z" }, + { url = "https://files.pythonhosted.org/packages/85/8c/e9960b996e70e5f6a523670431166b2b238de52fef094955515dcf854da1/atheris-3.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:510e502c57b6dc615fb174066407af620d4c7f73cf08a782c86e7761bf12c4eb", size = 34907016, upload-time = "2025-11-24T23:53:56.535Z" }, + { url = "https://files.pythonhosted.org/packages/db/48/df670f75f458cc7c1752a01a394fd59c830b08172dd59cf29d73f31050f9/atheris-3.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a402cdca8a650d1371050b1f9552eb4cdc488d2db64950d603c4560318365eac", size = 34858525, upload-time = "2025-11-24T23:53:59.925Z" }, ] [[package]] name = "atheris" version = "3.1.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11.5'", +] wheels = [ { url = "https://files.pythonhosted.org/packages/0a/88/fd6ad595dafa9c7ce56dbfcaff0c7244988dac3af86c771166c6516ccf6b/atheris-3.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ec5e11f21a4c197fe91f7aea2b2de88e623c73a21fc07b105ac6329a1588457b", size = 36875908, upload-time = "2026-06-17T00:04:01.104Z" }, { url = "https://files.pythonhosted.org/packages/4e/18/e19718c384fd7d801d0da7485407daef9af6194b6d8c8818175bec5efec6/atheris-3.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f8a9f51ce8369026e8eb7b7174835e8c4c85a1a6db5d9add36c15100779d2a39", size = 36800563, upload-time = "2026-06-17T00:04:04.559Z" }, @@ -164,30 +177,30 @@ wheels = [ [[package]] name = "boto3" -version = "1.43.119" +version = "1.43.123" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "botocore" }, { name = "jmespath" }, { name = "s3transfer" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/02/1b/97f8ec6ce00ae49455797b8af9fde522624ecf80bc73c937596b558b1853/boto3-1.43.119.tar.gz", hash = "sha256:e12c3b1d81713e14bd6947b7412d9d0ea49b320642d795ded1d64d6483ca6f49", size = 112659, upload-time = "2026-10-26T19:25:58.76Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fc/8a/64b46f075149f9160da44aa7e1052dd18431b9ad4435beb0cfb02cc48624/boto3-1.43.123.tar.gz", hash = "sha256:055fabb990c5d2f31fce4ca569255bd640cdd11a3ca68c9ecad35f4f8a5b83b5", size = 112638, upload-time = "2026-10-30T19:18:50.085Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3a/d7/6c82dff652082a4bab907b7a5833933a362f12400f14bd7a9935a330145e/boto3-1.43.119-py3-none-any.whl", hash = "sha256:d1718edae48c3241d289c0ece8a515399a7242c406e35328b9685c4d24039186", size = 140045, upload-time = "2026-10-26T19:25:57.128Z" }, + { url = "https://files.pythonhosted.org/packages/96/b2/a7986c327f80aa6f1544f4cb8f2fa7da4e1fccd472379a21cad0508b8a0e/boto3-1.43.123-py3-none-any.whl", hash = "sha256:d18d66e1e13faa0c25d0b1b8c5ce946e29fb5fc0b6456b655a93a678ff4cc313", size = 140044, upload-time = "2026-10-30T19:18:47.734Z" }, ] [[package]] name = "botocore" -version = "1.43.119" +version = "1.43.123" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jmespath" }, { name = "python-dateutil" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a8/ab/8e6d1d97c086c127f725cdeffae3b44d92ca3ca40741fb90f245f11887d5/botocore-1.43.119.tar.gz", hash = "sha256:ed11934be6e6d398ac21b7fe03778c9584368eeff8ba5371581f19bb47db0b6a", size = 16457548, upload-time = "2026-10-26T19:25:52.703Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/de/011fc2a47fb066c47064b122498d2fd21f55bc90ea514acbddc37ca0f8c1/botocore-1.43.123.tar.gz", hash = "sha256:80948cb9b1cdf1a1a25809089a42e3a1bc4af0258d198222db6e97dcc660dd0c", size = 16486269, upload-time = "2026-10-30T19:18:44.609Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/54/04e5950c7f2d22d78f22db00ca119b257b7cd2024328b6116ebaeb9c14eb/botocore-1.43.119-py3-none-any.whl", hash = "sha256:6026aec97914a4fa116915fd3b05af899912eff51b93fb8dff95aa228a3e761b", size = 16154402, upload-time = "2026-10-26T19:25:48.301Z" }, + { url = "https://files.pythonhosted.org/packages/db/96/4f2dffd304425c07160ab2c12cb13322d852fd956fe9d4386228c93f02ea/botocore-1.43.123-py3-none-any.whl", hash = "sha256:e30580f9c1282c321529238ff8ff75066096a2adbd0a293c8ae592c21d1733a3", size = 16185987, upload-time = "2026-10-30T19:18:39.794Z" }, ] [[package]] @@ -765,11 +778,11 @@ wheels = [ [[package]] name = "dnspython" -version = "2.9.0" +version = "2.9.1" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/ef/4a/50822184bd67cc6493f0fb6a880749158fcd31ab3fa07409acfd91f9fc85/dnspython-2.9.0.tar.gz", hash = "sha256:b44dc6b18f07a8b1c56676a19fbfdb5209415b046a9cece286baafa87ff3f7f1", size = 423560, upload-time = "2026-10-09T00:07:24.352Z" } +sdist = { url = "https://files.pythonhosted.org/packages/91/21/7fcd6780f61e9756aafaea760560509bb4111375daa2e23c1be7a89f33f1/dnspython-2.9.1.tar.gz", hash = "sha256:9a6d30e55f8dc63e6052597666112bff0586b95a2474a9deda03afbbf820d37a", size = 455302, upload-time = "2026-10-29T18:05:12.156Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/10/02/cdcc9b7c051786a103c3b09e1003a82fa0c66bcb91ffbdabcfbf7b4163b9/dnspython-2.9.0-py3-none-any.whl", hash = "sha256:9a4aedb833c3c1b49214d04d44d3032ab7a9135f7c1d29a549b4ff78fd82fda9", size = 354822, upload-time = "2026-10-09T00:07:22.622Z" }, + { url = "https://files.pythonhosted.org/packages/61/55/f90405bbbbd3dd8f788e92cec2d39964f5c09783f0570fc35f3bb3381485/dnspython-2.9.1-py3-none-any.whl", hash = "sha256:7c81caf8de1ed57b8cfc7e0ad4f528a0b8ceace473c7eb946df195dc9def751f", size = 360364, upload-time = "2026-10-29T18:05:10.206Z" }, ] [[package]] @@ -1335,11 +1348,11 @@ wheels = [ [[package]] name = "nodeenv" -version = "1.11.0" +version = "1.12.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/105de02c1322cfada6d9710d9146ef8026419d433c9d08359a2d35805811/nodeenv-1.11.0.tar.gz", hash = "sha256:3ce8fe5b71d16e8af7039ca65257354100bc772965d6bc549070649e53b1b146", size = 99301, upload-time = "2026-09-26T11:29:21.367Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e6/99/d27cfc9518f49e4cbc25c683ec7cf8704a9d31311341c291c0e78ddf791b/nodeenv-1.12.0.tar.gz", hash = "sha256:4ea7f88339310afebc3253f2c7a91b94bacf97d73a36a5c108962abdfaca501e", size = 131292, upload-time = "2026-10-31T19:03:18.847Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/54/c8/12811c9b48fde162bb72b6f2e78fada9a247a09d7bb5be2050a5d099c77b/nodeenv-1.11.0-py2.py3-none-any.whl", hash = "sha256:edaa16e6c14d7cf395d75d4bbd5a26390f4dc06501a33b4e76282b02cc688a25", size = 34277, upload-time = "2026-09-26T11:29:19.933Z" }, + { url = "https://files.pythonhosted.org/packages/2d/6a/8a9ac7d5e2f7cf53c459bfef90ebc17a2f8cd54b665af96799d4c534840e/nodeenv-1.12.0-py3-none-any.whl", hash = "sha256:80644d65c10cc2be12e3e4b54b3367ff288c7ad24ae75c2dcc65454fc7449d4d", size = 39442, upload-time = "2026-10-31T19:03:17.427Z" }, ] [[package]] @@ -1362,11 +1375,11 @@ wheels = [ [[package]] name = "pip" -version = "26.2.2" +version = "26.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fa/e8/0842d757e483e895e670f655084cfe8b8c72580c6769a76b30b2789a0608/pip-26.2.2.tar.gz", hash = "sha256:3a8e5c800492787f33a4114ef54444546c340df428974ebba17e0fd47e11af2f", size = 1863336, upload-time = "2026-10-20T16:36:29.008Z" } +sdist = { url = "https://files.pythonhosted.org/packages/53/c7/f8d9e2e0e7c1ed8a22a10eeb3b5bf7860bc07d8446c7a978a882c5c8214b/pip-26.3.tar.gz", hash = "sha256:6c36ae7da8695be67e3cd9f7d87919667ced53f57ce2ede75d89b5912ed2bc4c", size = 1934348, upload-time = "2026-11-02T20:34:27.738Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl", hash = "sha256:fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70", size = 1819850, upload-time = "2026-10-20T16:36:27.046Z" }, + { url = "https://files.pythonhosted.org/packages/07/25/ee8c38ae72d66b844ce8eb9711ba905dba21ca1a8a0c960057c41cd23337/pip-26.3-py3-none-any.whl", hash = "sha256:f3b60b20ffaadd4415ed7957212a38ac63fa4c5fa375bd0f4a797777940fad13", size = 1950951, upload-time = "2026-11-02T20:34:25.728Z" }, ] [[package]] @@ -1454,7 +1467,8 @@ coverage = [ { name = "coverage", extra = ["toml"] }, ] fuzz = [ - { name = "atheris" }, + { name = "atheris", version = "3.0.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11.5'" }, + { name = "atheris", version = "3.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11.5'" }, ] gevent = [ { name = "gevent" }, @@ -1494,7 +1508,7 @@ requires-dist = [ { name = "pykerberos", marker = "os_name != 'nt' and extra == 'gssapi'", specifier = ">=1.2.4" }, { name = "pymongo-auth-aws", marker = "extra == 'aws'", specifier = ">=1.3.0,<2.0.0" }, { name = "pymongo-auth-aws", marker = "extra == 'encryption'", specifier = ">=1.3.0,<2.0.0" }, - { name = "pymongocrypt", marker = "extra == 'encryption'", specifier = ">=1.18.1,<2.0.0" }, + { name = "pymongocrypt", marker = "extra == 'encryption'", specifier = ">=1.21.0,<2.0.0" }, { name = "pyopenssl", marker = "extra == 'ocsp'", specifier = ">=26.2.0" }, { name = "pytest", marker = "extra == 'test'", specifier = ">=8.2" }, { name = "pytest-asyncio", marker = "extra == 'test'", specifier = ">=0.24.0" }, @@ -1515,7 +1529,7 @@ coverage = [{ name = "coverage", extras = ["toml"], specifier = ">=6.4,<=7.15.0" dev = [] fuzz = [{ name = "atheris", specifier = ">=2.3.0" }] gevent = [{ name = "gevent", specifier = ">=25.9.1" }] -lint = [{ name = "ruff", specifier = "==0.15.20" }] +lint = [{ name = "ruff", specifier = "==0.17.3" }] mockupdb = [{ name = "mockupdb", specifier = ">=1.8.1" }] perf = [{ name = "simplejson", specifier = ">=3.17.0" }] pip = [{ name = "pip", specifier = ">=20.2" }] @@ -1526,7 +1540,7 @@ typing = [ { name = "typing-extensions", specifier = ">=3.7.4.2" }, ] unasync = [ - { name = "ruff", specifier = "==0.15.20" }, + { name = "ruff", specifier = "==0.17.3" }, { name = "unasync" }, ] @@ -1589,7 +1603,7 @@ wheels = [ [[package]] name = "pytest" -version = "9.1.1" +version = "9.2.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "colorama", marker = "sys_platform == 'win32'" }, @@ -1598,22 +1612,22 @@ dependencies = [ { name = "pluggy" }, { name = "pygments" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e4/47/b9efed96c114afcfa3c9d3fe98a76a1d14c74a9e266d397cf6eb64be5e01/pytest-9.1.1.tar.gz", hash = "sha256:1088fbde8f2b49d95a549a195707afa7a76a3ce9bcadc26b6d71f0ffda5fe313", size = 1636369, upload-time = "2026-06-19T10:58:32.857Z" } +sdist = { url = "https://files.pythonhosted.org/packages/79/42/bb4641652e58dedeac2ec51abc1f8cae4fee4ec63899a0999016229a0f2a/pytest-9.2.0.tar.gz", hash = "sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b", size = 1797555, upload-time = "2026-10-27T21:30:20.728Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, + { url = "https://files.pythonhosted.org/packages/51/39/1f5d8c8877a0fa327db959c19341d4be61660de1ab6b7391f9eb805bcd67/pytest-9.2.0-py3-none-any.whl", hash = "sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588", size = 411776, upload-time = "2026-10-27T21:30:19.131Z" }, ] [[package]] name = "pytest-asyncio" -version = "1.4.1" +version = "1.4.1.post1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "pytest" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f8/9a/887535e477847f5159377ab35303923644840b13c0ca03c0a467f84d4680/pytest_asyncio-1.4.1.tar.gz", hash = "sha256:e8266eb094e5ee9ffdb2068c9836f33e209ea77a970eb846933d416b5602669b", size = 145237, upload-time = "2026-10-25T21:05:37.135Z" } +sdist = { url = "https://files.pythonhosted.org/packages/73/7f/c60a4338420b33453d4f814ac0c930abd399f162b9bdd21af4b9e363037f/pytest_asyncio-1.4.1.post1.tar.gz", hash = "sha256:f582d9ea4a1c082195abe8bd29a1fe106aeb1cd435e3dad2d3bc2749935c36a2", size = 145360, upload-time = "2026-11-01T18:26:03.732Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/46/d7/cd9e2708afdbf059658adaf08bdb0792ca52489871051d6ce7d498b51277/pytest_asyncio-1.4.1-py3-none-any.whl", hash = "sha256:507afa78ec77c6661164ef1a2368bc7820383fd1a14b2a7f813de8b5a92949cc", size = 17061, upload-time = "2026-10-25T21:05:35.473Z" }, + { url = "https://files.pythonhosted.org/packages/e3/de/adbc7578959cfab07e5e7c05cf6d54224a51e7667ea2c07458b6bc571e75/pytest_asyncio-1.4.1.post1-py3-none-any.whl", hash = "sha256:0755e488cc0a2b9bd2eab7292cc6390d4cbb8390f1020745647bae5a708e0165", size = 17140, upload-time = "2026-11-01T18:26:02.168Z" }, ] [[package]] @@ -1687,27 +1701,27 @@ wheels = [ [[package]] name = "ruff" -version = "0.15.20" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/43/dc/35b341fc554ba02f217fc10da57d1a75168cfbcf75b0ef2202176d4c4f2d/ruff-0.15.20.tar.gz", hash = "sha256:1416eb04349192646b54de98f146c4f59afe37d0decfc02c3cbbf396f3a28566", size = 4755489, upload-time = "2026-06-25T17:20:37.578Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/94/d9/2d5014f0253ba541d2061d9fa7193f48e941c8b21bb88a7ff9bbe0bd0596/ruff-0.15.20-py3-none-linux_armv6l.whl", hash = "sha256:00e188c53e499c3c1637f73c91dcf2fb56d576cab76ce1be50a27c4e80e37078", size = 10839665, upload-time = "2026-06-25T17:19:44.702Z" }, - { url = "https://files.pythonhosted.org/packages/c6/d3/ac1798ba64f670698867fcfc591d50e7e421bef137db564858f619a30fcf/ruff-0.15.20-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:9ebd1fd9b9c95fc0bd7b2761aebec1f030013d2e193a2901b224af68fe47251b", size = 11208649, upload-time = "2026-06-25T17:19:48.787Z" }, - { url = "https://files.pythonhosted.org/packages/47/47/d3ac899991202095dfcf3d5176be4272642be3cf981a2f1a30f72a2afb95/ruff-0.15.20-py3-none-macosx_11_0_arm64.whl", hash = "sha256:c5b16cdd67ca108185cd36dce98c576350c03b1660a751de725fb049193a0632", size = 10622638, upload-time = "2026-06-25T17:19:51.354Z" }, - { url = "https://files.pythonhosted.org/packages/33/13/4e043fe30aa94d4ff5213a9881fc296d12960f5971b234a5263fdc225312/ruff-0.15.20-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3413bb3c3d2ca6a8208f1f4809cd2dca3c6de6d0b491c0e70847672bde6e6efd", size = 10984227, upload-time = "2026-06-25T17:19:54.044Z" }, - { url = "https://files.pythonhosted.org/packages/76/e6/92e7bf40388bc5800073b96564f56264f7e48bfd1a498f5ced6ae6d5a769/ruff-0.15.20-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:bd7ec42b3bb3da066488db093308a69c4ac5ee6d2af333a86ba6e2eb2e7dd44b", size = 10622882, upload-time = "2026-06-25T17:19:57.037Z" }, - { url = "https://files.pythonhosted.org/packages/13/7a/43460be3f24495a3aa46d4b16873e2c4941b3b5f0b00cf88c03b7b94b339/ruff-0.15.20-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e1a36ad0eb77fba9aabfb69ede54de6f376d04ac18ebea022847046d340a8267", size = 11474808, upload-time = "2026-06-25T17:20:00.357Z" }, - { url = "https://files.pythonhosted.org/packages/27/a0/f37077884873221c6b33b4ab49eb18f9f88e54a16a25a5bca59bef46dd66/ruff-0.15.20-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b6df3b1e4610432f0386dba04d853b5f08cbbc903410c6fcc02f620f05aff53c", size = 12293094, upload-time = "2026-06-25T17:20:03.446Z" }, - { url = "https://files.pythonhosted.org/packages/a6/74/165545b60256a9704c21ac0ec4a0d07933b320812f9584836c9f4aca4292/ruff-0.15.20-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e89f198a1ea6ef0d727c1cf16088bc91a6cb0ab947dedc966715691647186eae", size = 11526176, upload-time = "2026-06-25T17:20:06.301Z" }, - { url = "https://files.pythonhosted.org/packages/86/b1/a976a136d40ade83ce743578399865f57001003a409acadc0ecbb3051082/ruff-0.15.20-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:309809086c2acb67624950a3c8133e80f32d0d3e27106c0cd60ff26657c9f24b", size = 11520767, upload-time = "2026-06-25T17:20:09.191Z" }, - { url = "https://files.pythonhosted.org/packages/19/0f/f032696cb01c9b54c0263fa393474d7758f1cdc021a01b04e3cbc2500999/ruff-0.15.20-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:2d2374caa2f2c2f9e2b7da0a50802cfb8b79f55a9b5e49379f564544fbf56487", size = 11500132, upload-time = "2026-06-25T17:20:13.602Z" }, - { url = "https://files.pythonhosted.org/packages/4b/f4/51b1a14bc69e8c224b15dab9cce8e99b425e0455d462caa2b3c9be2b6a8e/ruff-0.15.20-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:a1ed17b65293e0c2f22fc387bc13198a5de94bf4429589b0ff6946b0feaf21a3", size = 10943828, upload-time = "2026-06-25T17:20:16.635Z" }, - { url = "https://files.pythonhosted.org/packages/71/4b/fe267640783cd02bf6c5cc290b1df1051be2ec294c678b5c15fe19e52343/ruff-0.15.20-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:f701305e66b38ea6c91882490eb73459796808e4c6362a1b765255e0cdcd4053", size = 10645418, upload-time = "2026-06-25T17:20:19.4Z" }, - { url = "https://files.pythonhosted.org/packages/b0/c0/a65aa4ec2f5e87a1df32dc3ec1fede434fe3dfd5cbcf3b503cafc676ab54/ruff-0.15.20-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5b9c0c367ad8e5d0d5b5b8537864c469a0a0e55417aadfbeca41fa61333be9f4", size = 11211770, upload-time = "2026-06-25T17:20:22.033Z" }, - { url = "https://files.pythonhosted.org/packages/5a/a4/0caa331d954ae2723d729d351c989cb4ca8b6077d5c6c2cb6de75e98c041/ruff-0.15.20-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:01cc00dd58f0df339d0e902219dd53990ea99996a0344e5d9cc8d45d5307e460", size = 11618698, upload-time = "2026-06-25T17:20:25.259Z" }, - { url = "https://files.pythonhosted.org/packages/10/9b/5f14927848d2fd4aa891fd88d883788c5a7baba561c7874732364045708c/ruff-0.15.20-py3-none-win32.whl", hash = "sha256:ed65ef510e43a137207e0f01cfcf998aeddb1aeeda5c9d35023e910284d7cf21", size = 10857322, upload-time = "2026-06-25T17:20:28.612Z" }, - { url = "https://files.pythonhosted.org/packages/fa/f0/fe47c501f9dea92a26d788ff98bb5d92ed4cb4c88792c5c88af6b697dc8e/ruff-0.15.20-py3-none-win_amd64.whl", hash = "sha256:a525c81c70fb0380344dd1d8745d8cc1c890b7fc94a58d5a07bd8eb9557b8415", size = 11993274, upload-time = "2026-06-25T17:20:31.871Z" }, - { url = "https://files.pythonhosted.org/packages/d7/2b/9555445e1201d92b3195f45cdb153a0b68f24e0a4273f6e3d5ab46e212bb/ruff-0.15.20-py3-none-win_arm64.whl", hash = "sha256:2f5b2a6d614e8700388806a14996c40fab2c47b819ef57d790a34878858ed9ca", size = 11343498, upload-time = "2026-06-25T17:20:35.03Z" }, +version = "0.17.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/59/73/81f140c4edd9cc323de5478e6bbd3bbcfae9a82692df1a258de8cec6a6d2/ruff-0.17.3.tar.gz", hash = "sha256:a57049c8addb3662073859bb55a7ad35aa54f8a7c9ed268911d1333c5aadaaa9", size = 5339444, upload-time = "2026-10-27T00:34:05.914Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/8c/083365310c4e79c842f25bf5a842facbd9b0c0ec336f96dffa5074fe723d/ruff-0.17.3-py3-none-linux_armv6l.whl", hash = "sha256:ab86b84cd9d05e56d329742c0cabdcbe2d1d56c98f4a04aab9b5b66196febfb4", size = 10216522, upload-time = "2026-10-27T00:33:29.822Z" }, + { url = "https://files.pythonhosted.org/packages/72/26/4b2edf31cfebe9605d8f6ed8f1d6f376d3a53d4c9a123e62661c64c440f0/ruff-0.17.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e407b4a6852853a9a2cdce96963e94ad9775578bb44e7561a0f2829f3cc04b11", size = 10217786, upload-time = "2026-10-27T00:33:33.949Z" }, + { url = "https://files.pythonhosted.org/packages/a2/7e/537aba4b7f54397a374d2f6a6fc93e9c8015e18553f31a4a7b7dbced48b5/ruff-0.17.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:b75cc113b3aca388933d8296b667b1ac401a80317ea3074c9b0a66541199da29", size = 9440362, upload-time = "2026-10-27T00:33:35.784Z" }, + { url = "https://files.pythonhosted.org/packages/3d/66/283e39734f66c8a5ebaa93c22eb7b7515779a0b1d5a5c0ad20e05c0edb41/ruff-0.17.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab5fa7ed5ce18554ea69d850ad162cbaa0c85fc47c08d83a569f806681c9a6ad", size = 10094281, upload-time = "2026-10-27T00:33:38.216Z" }, + { url = "https://files.pythonhosted.org/packages/21/4c/1ffc768497bd025a32c72152771e40c0b99bddc5cc6e4f50c7949a395346/ruff-0.17.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c673c170e27834d1262e3a9c1e97bdc9b9c3b180c63d89173ce69747232474c1", size = 10022543, upload-time = "2026-10-27T00:33:40.181Z" }, + { url = "https://files.pythonhosted.org/packages/73/c3/f90db547301080fcb82c92abf914c8bd57b89911d9b65a6c4cc6b52d0635/ruff-0.17.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a754c0341bc9ca151b7b335988b3263921c08859f84ca219b70cee825571b6f", size = 10683921, upload-time = "2026-10-27T00:33:42.182Z" }, + { url = "https://files.pythonhosted.org/packages/e5/98/92d4a8a26c6c96cf1a5b34dd59036d8a71e52d650aab065c58867e964e63/ruff-0.17.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:4590b9d86c0b1543ebb09094254e191cd43fe8edaf330baa035aab03da251532", size = 11373408, upload-time = "2026-10-27T00:33:44.19Z" }, + { url = "https://files.pythonhosted.org/packages/43/02/1f24d2e3064c9753926deeb901afa57777b37ee46799b09ddd7aee6e5145/ruff-0.17.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:bbde18beccd98c29a227c63c99022e3443b99258e08326df6425dfe0443705ef", size = 10977469, upload-time = "2026-10-27T00:33:46.179Z" }, + { url = "https://files.pythonhosted.org/packages/f0/20/fecedea2209f574ab92033b344e01a7f0c2dc76c6d6d19a14c9f8141173f/ruff-0.17.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7fa4b0f931cdbcb8a52044f370a3eb429fb42eb88807b0e800fcaa98dd42b24e", size = 10577491, upload-time = "2026-10-27T00:33:48.233Z" }, + { url = "https://files.pythonhosted.org/packages/33/36/b93fdf0bc6f84f0cd487aadfb0354deb40013669ea35ac3d26855de1e959/ruff-0.17.3-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:39405f341deec934b4289634324ad695f72df2970f9121582872eaf5b722f0f5", size = 10608748, upload-time = "2026-10-27T00:33:50.284Z" }, + { url = "https://files.pythonhosted.org/packages/5d/b7/7d3f5f14145daead1efb0b9a8289ed1daa100f419d60774375951723ce00/ruff-0.17.3-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:68074094f55ca3d29ab19491f640282f7a84061c4c7977aa5094b968ca457e9a", size = 10075057, upload-time = "2026-10-27T00:33:52.074Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ed/93ff7a5909ee56e2bd4b982deae9e0efb2724417874a90c9e41ad66c6dd7/ruff-0.17.3-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:27bb571ac78fef178fe5118d2827df95c2aae74a48fff2b15f6acd03af5ff5bb", size = 10022431, upload-time = "2026-10-27T00:33:54.061Z" }, + { url = "https://files.pythonhosted.org/packages/9b/07/a83b9eeec8c1c3c0e4eda15f06c3a91001bfd2687ea2f07b750719bf9712/ruff-0.17.3-py3-none-musllinux_1_2_i686.whl", hash = "sha256:029c37cbd3de48ca37aa12117bead2d065f15da17d66bf84e0d4274013705db2", size = 10394903, upload-time = "2026-10-27T00:33:56.158Z" }, + { url = "https://files.pythonhosted.org/packages/af/b2/05c39857c2526fcbebe46ad93a8dc97424656dfef14d3ef933abe1ffd331/ruff-0.17.3-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:692fdb46d0fd9c71e380947dc5fc72f2c3f881073bc1f739e4579376231affbe", size = 10799780, upload-time = "2026-10-27T00:33:58.204Z" }, + { url = "https://files.pythonhosted.org/packages/ec/d9/47171a16739eb7a353936b31c20cf54340531e68c9af7d72fd7a784e235d/ruff-0.17.3-py3-none-win32.whl", hash = "sha256:46539cb031b01fd29ae0a02142483c46640b233ee12bb1c1b690bffa1555d5ca", size = 9908481, upload-time = "2026-10-27T00:34:00.087Z" }, + { url = "https://files.pythonhosted.org/packages/d0/a0/f08c1631bfd81faa6a90eaf70c37c786c11bed2046302b56bb506c25e1a0/ruff-0.17.3-py3-none-win_amd64.whl", hash = "sha256:56b8ffb3f3b3cbccb8b76b71b38261b7ed982ef5d20f5b447b1b61a7f4949b24", size = 10341333, upload-time = "2026-10-27T00:34:02.099Z" }, + { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, ] [[package]] @@ -2227,163 +2241,163 @@ wheels = [ [[package]] name = "websockets" -version = "17.3" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/30/4b/4692be6d5bf739ed049b3813901c42091f8c054df89d5c089343823dea0d/websockets-17.3.tar.gz", hash = "sha256:1c7dd93a1c9f89297471493674b1fc1d9467cafd45374f2172213046bdb3a329", size = 188878, upload-time = "2026-10-19T16:58:05.813Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/b8/282f114a67886fccde02a77ff296501ad7fea25f4d696b2b1b337cbd27da/websockets-17.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:45cc1ccb12ced6d242335159e8221733c8696da5ad0b6ceef6debb0f5ce89110", size = 218223, upload-time = "2026-10-19T16:54:25.998Z" }, - { url = "https://files.pythonhosted.org/packages/8b/ba/8043c303aa60af053e092c1d667165f46d6729217ce2af795a23a3cd700a/websockets-17.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:46ae05aa1aecd47d4d7de0f05ce2d1d2eb418f8de614964d754cc3b9a409c400", size = 215908, upload-time = "2026-10-19T16:54:27.785Z" }, - { url = "https://files.pythonhosted.org/packages/21/3d/5d0eaa9b29db6c999a2cf749605141796cff21a5e235b2488bd39dcdcac9/websockets-17.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:43f270a5f21e12db08c73d83849a877c02ab7b7d0fb6e2718b5101d9c810212f", size = 216181, upload-time = "2026-10-19T16:54:29.267Z" }, - { url = "https://files.pythonhosted.org/packages/43/fb/33080a7b2d8427b343056eab32ba78235a4bfbbdc79b5593688c7b7c62ef/websockets-17.3-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:2d875224bac1a05a20acade268a7a0e3498e7f8cf890acb7c2b23bacd2bd3659", size = 225246, upload-time = "2026-10-19T16:54:30.807Z" }, - { url = "https://files.pythonhosted.org/packages/61/8c/d4220455cee00adb553c602ba4f1f6a47cd882d86dd9e5124679c0c95c75/websockets-17.3-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:5ad409b7ea102339041281117cf2dadfe71edbb653dc48037cc55d516fb7f448", size = 225517, upload-time = "2026-10-19T16:54:32.182Z" }, - { url = "https://files.pythonhosted.org/packages/75/a3/0ff8e4f0195884ae446844185e81bf7619673d816424b8a58bb5812dd4b8/websockets-17.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d43c311f3519fb1057b6114dc24e9060bc3fb6aedf4aa11160484154b66b63", size = 226751, upload-time = "2026-10-19T16:54:33.52Z" }, - { url = "https://files.pythonhosted.org/packages/06/cf/82c88e3fbb6a75a62b2997932664bccfe68256661c69144bd48020160cf1/websockets-17.3-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a9eacb382f400bb5865e7e6d24bbe709a84510291e707f169dd4a24ee4a5ac6a", size = 230063, upload-time = "2026-10-19T16:54:34.855Z" }, - { url = "https://files.pythonhosted.org/packages/4a/e4/9131d3b73504902a83d10b1e1244319377ca72755351998ac9c408ba6ddb/websockets-17.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f09f145b89ea292cf6c25fd7c8c0d90207fd6a9e54c7828499669996a1e5bdcc", size = 227310, upload-time = "2026-10-19T16:54:36.248Z" }, - { url = "https://files.pythonhosted.org/packages/ca/b2/2208506afb45d181b0d6ccf377d9d79985fbcbf871af02ef4f7f3d405f5b/websockets-17.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:49fb5b4960ebe1bc557b435da8687deef1302a08f030a33c5606fa6fb11b773b", size = 226087, upload-time = "2026-10-19T16:54:37.583Z" }, - { url = "https://files.pythonhosted.org/packages/39/53/da73e3809f1d4e8c3346ca89a4bed7995de5708f2cb14c9359172a85f5a5/websockets-17.3-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:13cffaedde6e06183860fc92d88fe1d190abda73837fe4c14f5d4803c472f5dd", size = 223360, upload-time = "2026-10-19T16:54:38.91Z" }, - { url = "https://files.pythonhosted.org/packages/9a/7b/eaf828fd414401672e615570b9f2bfd84342b49c86ffb2ae735e4aada32f/websockets-17.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ef2950896673a9809e8e5ab857525924fbcacfc98b858b0509ccf50d341f80f4", size = 226240, upload-time = "2026-10-19T16:54:40.294Z" }, - { url = "https://files.pythonhosted.org/packages/79/bd/4b6aa6e761c8d89aa6defdd83e40a6b2d9aa21bd01520c8e8470fe8d8681/websockets-17.3-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2d08ca4bf5a9cdb6fd81b86b51bd5cfb10527d3a1199888f2b02cc6c6a3d5f80", size = 224833, upload-time = "2026-10-19T16:54:41.939Z" }, - { url = "https://files.pythonhosted.org/packages/37/a8/0a6aea08cad7db2c1aa53dbd3ece3ebc09e420e8301cb02f2b812a728a5b/websockets-17.3-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5e0c0ed37472c4729f3001066510a656486f08f149dda1ebfd3dfe4450c9756e", size = 225599, upload-time = "2026-10-19T16:54:43.54Z" }, - { url = "https://files.pythonhosted.org/packages/1d/82/3998ea56beb079f43fc39dd5935ef8dc150f915bf2de8bd6ddcd50c0fae6/websockets-17.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:62059d739af7fc035ed6e63c5390118a60a5e9aa5a5541cd0486a83e741842c7", size = 226643, upload-time = "2026-10-19T16:54:44.914Z" }, - { url = "https://files.pythonhosted.org/packages/c1/a5/6568add8d0a2f37c5780c6de62b5b8ee191ca9d2d0b8ff2123b8277c41b7/websockets-17.3-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:bc6f87d03e3691154673aaa8f08991723d6e3394c83ef2875c7a9049eac9595c", size = 224223, upload-time = "2026-10-19T16:54:46.429Z" }, - { url = "https://files.pythonhosted.org/packages/72/79/b11bc05b0f64d8b14901443a4b01ea80d039cc68b260250b4cb488070aca/websockets-17.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:3d78d93846eddc990551c1c31914d90d71957ca3af468969826f7ed0d7d1d51c", size = 225255, upload-time = "2026-10-19T16:54:47.82Z" }, - { url = "https://files.pythonhosted.org/packages/71/f9/9a8902074db7044b64a05feff349e4f44144a961310d3419bab612f00dd1/websockets-17.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:2a377c7132b1e69be7a50d7434d7f26f69e93c70166ebb6d8f8cabf802ac4506", size = 225494, upload-time = "2026-10-19T16:54:49.171Z" }, - { url = "https://files.pythonhosted.org/packages/99/ba/7b873060ce6764207a24c10e81294739abffe2a90dc67c7f7db5042c596c/websockets-17.3-cp311-cp311-win32.whl", hash = "sha256:29b01520c39ef2f23c88b002f11e6ef4165675f6c92f5f3578fd587d69b5a5fc", size = 218720, upload-time = "2026-10-19T16:54:50.501Z" }, - { url = "https://files.pythonhosted.org/packages/28/11/7469f3f28513ec0d43f10b1c88bf970b0b6f0aa8190c42731954297e824c/websockets-17.3-cp311-cp311-win_amd64.whl", hash = "sha256:d338813a440bf6d2f0df55140d3f3080284410b1ebfe9df50e3847bcdb1a17bb", size = 219017, upload-time = "2026-10-19T16:54:51.843Z" }, - { url = "https://files.pythonhosted.org/packages/bc/fd/4724610baabbba94a44c5d1cf1b1a33ff77031e94a51addb0387c7f56b10/websockets-17.3-cp311-cp311-win_arm64.whl", hash = "sha256:6a8248b1ba8861e48e4c7ced3895a1264d2a3b617de72ec94172ce6e64bf16c7", size = 218950, upload-time = "2026-10-19T16:54:53.37Z" }, - { url = "https://files.pythonhosted.org/packages/0d/29/902ffe19c0d35603102f31490dea342f083bc77d8f8bcdc7d8b16f5810f9/websockets-17.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:41665c7ea01d3ae497a0c61fd22d3424230d18782a5fceb79f04db9ccb2042c9", size = 218250, upload-time = "2026-10-19T16:54:54.718Z" }, - { url = "https://files.pythonhosted.org/packages/f0/66/f56a2637b1aac263205b0e3cd7b2ff2e2f8b404b8118c991f4d122fd381f/websockets-17.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8f7469408740cf06a79b01605f2ae0b2acc8839c03fcbbf05da49baee12d3302", size = 215927, upload-time = "2026-10-19T16:54:56.124Z" }, - { url = "https://files.pythonhosted.org/packages/22/7d/a27f25451c4cc62141992b51005688481210f3d3e63de3dc66f9e882ba59/websockets-17.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d68da281ac208b6236ffa8beef23fe7c7c956d8bf09b421d447232fd94441b35", size = 216196, upload-time = "2026-10-19T16:54:57.538Z" }, - { url = "https://files.pythonhosted.org/packages/9f/77/40bbc1a5c016cf9f598dea21d1250a93245c995eafaec6401d0e4eb4e647/websockets-17.3-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:078d1d41f45ee34eed5a4f3bbe7c588caecbdd6e12dfca73e8c1b0e803773793", size = 225516, upload-time = "2026-10-19T16:54:59.104Z" }, - { url = "https://files.pythonhosted.org/packages/3d/9c/91889c8c62fb7d16cd58e3074473a259303d6229bf0ce496aec87e66f3dc/websockets-17.3-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:a7f391838e8adcf1f2fe71561d9e5a9f74ea7ffa5052eb2db329aac677383136", size = 225795, upload-time = "2026-10-19T16:55:00.438Z" }, - { url = "https://files.pythonhosted.org/packages/b8/29/2e5e2158e9920f806cd45f3cbc81cf5f3eef2b9e5a74b9ef049e2a3578e3/websockets-17.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c15a165673bb3fb57facbf040edf5c0556d20ccd2e0ccc5f23ebb69fb715fdc1", size = 227034, upload-time = "2026-10-19T16:55:02.065Z" }, - { url = "https://files.pythonhosted.org/packages/b6/af/fbab5c4098b26026b877bfc139b1ea0d7c6eaf7a86b84544933b4c445f82/websockets-17.3-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:28d1935c16782a1e3650c9baa79069b016fff739e292e4cb14bbb830d6930491", size = 229863, upload-time = "2026-10-19T16:55:03.415Z" }, - { url = "https://files.pythonhosted.org/packages/ac/72/d6e460a991607794072fe3fdfcb3221a0342af61586f5bd7ea40bddcfd21/websockets-17.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c534c9524a2acd0b97b7022074bec3784ac273c683cf9535087e437672ea8531", size = 227669, upload-time = "2026-10-19T16:55:04.763Z" }, - { url = "https://files.pythonhosted.org/packages/ec/8f/1c7da1cfb632e141e019cf2e0bbbd4e6dc8c198c8cc29544e4acf1a89f56/websockets-17.3-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b459d29c8b82a420a98fa0ce8e9cf787ce0062d98cc90604ef9574fb3cc26ff8", size = 226429, upload-time = "2026-10-19T16:55:06.112Z" }, - { url = "https://files.pythonhosted.org/packages/3e/63/c48ef8bbfbd982f2cfae1cfcf9e63f5bfbb8468fd37ca700507efc0b0007/websockets-17.3-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:53209dffd91b0aefed9ea630fa6ad5c2944d6210ba3a8a3a8664dc1575289b14", size = 223653, upload-time = "2026-10-19T16:55:07.473Z" }, - { url = "https://files.pythonhosted.org/packages/cb/37/7bedaad48ae8e89eaa4f3942c11be0c41de77ce2118a475f3ba05e9b5a0f/websockets-17.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9662a9fe457820c60365b3209e03cbd8e4a817195d55de65a80fa680b4bea136", size = 226465, upload-time = "2026-10-19T16:55:08.791Z" }, - { url = "https://files.pythonhosted.org/packages/33/cf/ab9a8a0de4769ca1dce392021b6a922e21b4d3687fe9e1ab4db585a088f8/websockets-17.3-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:5670a762c7ae388bf8aa04199fd436180a4d28318dca9c1eae7b38604676dbfd", size = 225071, upload-time = "2026-10-19T16:55:10.127Z" }, - { url = "https://files.pythonhosted.org/packages/89/96/64d8460cec95f873c61c6d13a09b435915150640525ae56d5871400aec09/websockets-17.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:ed59cb4ee258674a6ed9b8515e42079db02cb3be94f133fdd3f200183a40c49d", size = 225841, upload-time = "2026-10-19T16:55:11.519Z" }, - { url = "https://files.pythonhosted.org/packages/a6/98/2b83211ee3087db4ae66533782664c0e283cf4a08cbb14036018d0803e09/websockets-17.3-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:0f78bb2e82fe88912c9d7b25c98e57a9b08655579af89f164fd4c0657a075d62", size = 226945, upload-time = "2026-10-19T16:55:12.85Z" }, - { url = "https://files.pythonhosted.org/packages/9f/fe/6b2a37d422d7f4dfc0c92c95a14649d9bd662243ed8b0774523ed2703604/websockets-17.3-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:71250e010eede33c1d638e2c7a98288520d67f782fd5eceecaeca3129233a09a", size = 224502, upload-time = "2026-10-19T16:55:14.48Z" }, - { url = "https://files.pythonhosted.org/packages/0c/c5/364015c9311c89ea6085d54c70d654c5d27ba05014d44ef9fd9daa09462b/websockets-17.3-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:729989759feb81ff6493879a0d60a0bd7d2eee41001bbec0381a080318439382", size = 225483, upload-time = "2026-10-19T16:55:15.899Z" }, - { url = "https://files.pythonhosted.org/packages/c2/b3/75d0cae8398816ed34a16a78252bfc8651f2f883cc5a568e1198395f15df/websockets-17.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:90d8c4fa5ba293cf92de351fbc292cdaadb1a1d58d031a1a97ff9b8fb6250ec7", size = 225761, upload-time = "2026-10-19T16:55:17.28Z" }, - { url = "https://files.pythonhosted.org/packages/f0/af/9a7c4b2e87f47a2a6a066acdc2157e9b7cb6222a224b95a432f54ae786ce/websockets-17.3-cp312-cp312-win32.whl", hash = "sha256:0824e6ecee838cc28e6481062574c7fde49f9a2cedfacd36f0e91cb4b37fd6fe", size = 218722, upload-time = "2026-10-19T16:55:18.658Z" }, - { url = "https://files.pythonhosted.org/packages/f7/e8/e52953a8280a1e51cb9307218443f68c8f4dc4b9952db6021d5c12d03c0f/websockets-17.3-cp312-cp312-win_amd64.whl", hash = "sha256:6644eecd99c4e8cdf72e646e17b391bb70b054f44becde37dcdc48cbec7e1527", size = 219024, upload-time = "2026-10-19T16:55:19.987Z" }, - { url = "https://files.pythonhosted.org/packages/85/a4/005eb7c1f5c1a249c1231a6ed83a54ada0b6b8ffab33a608ca20e3034ea0/websockets-17.3-cp312-cp312-win_arm64.whl", hash = "sha256:4a9133dbaedc6f1af358127275676171d9a1bb3e61f47ee62b2ff9acb78af3d0", size = 218950, upload-time = "2026-10-19T16:55:22.161Z" }, - { url = "https://files.pythonhosted.org/packages/ee/1d/c1f4a1c45c5ca2c35ae9fd7cac0e491f8a014c9a86933a5da7b04ff825cf/websockets-17.3-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:52a2ca6f401fb49a8d5d9e0e48ade5f58f1bdda33132907b0e4e3b702628fa4e", size = 218243, upload-time = "2026-10-19T16:55:23.851Z" }, - { url = "https://files.pythonhosted.org/packages/4e/e8/f1b47d0ced4964ae748931a54347fd27b06b62e8ea7837a9de3aee0c5999/websockets-17.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:80578e91764bfca297ddca322c00a3136d993b829e9839e7fa378a19c1fcc25d", size = 215927, upload-time = "2026-10-19T16:55:25.317Z" }, - { url = "https://files.pythonhosted.org/packages/16/df/ab0ed0445d8d81a133c8fed760f3b4f743a2f563804fdbecb2c32fe05d94/websockets-17.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fe7a168d805c8a7bf1c2de55b7ab2bc958586bfd88d0e87235a92cac66b590a7", size = 216185, upload-time = "2026-10-19T16:55:26.678Z" }, - { url = "https://files.pythonhosted.org/packages/9f/51/b30fd6c5a33dac76a78083be125e3f9804f3d735da494ff03a46834f31f4/websockets-17.3-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:54fcd24944e6d127d198c28dc363967b7131ff0c97833962c2ef2048018de02d", size = 225574, upload-time = "2026-10-19T16:55:28.097Z" }, - { url = "https://files.pythonhosted.org/packages/1c/8a/8ede659919c0805d1fcc79c2ed16588d3419f1687c5117ba46f0217750ec/websockets-17.3-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:de2c12555bf05546f3ee75733f2c81de70aab7f530e86d0d2162b0ddcb3c39ae", size = 225854, upload-time = "2026-10-19T16:55:29.491Z" }, - { url = "https://files.pythonhosted.org/packages/a6/6a/e75d10e3896edc61320062890f71cdc0767dc4a54e2a26a943b703042d13/websockets-17.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c95d25b5382ee0e6191ecafdeabefdc1f7bff8dfee29239b9b79e760ef3b04bd", size = 227091, upload-time = "2026-10-19T16:55:31.146Z" }, - { url = "https://files.pythonhosted.org/packages/dc/d3/658f1e153566e5edae02812122d9f020c30785d8b53c4bda61b8e976f77f/websockets-17.3-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8f244dfee05ea29b8064701880865eb1684f3a704a5665bd10b64694444dbbd4", size = 228526, upload-time = "2026-10-19T16:55:32.524Z" }, - { url = "https://files.pythonhosted.org/packages/28/00/002f95a02d721d8c6ec2676c5aee904a823838a9c205fc0b31eedd882a7b/websockets-17.3-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e99440ef446c7833690c1754e23b0188d440f3cb89812b0764c697a7880cb33", size = 227718, upload-time = "2026-10-19T16:55:34.085Z" }, - { url = "https://files.pythonhosted.org/packages/fa/9c/d36ec9499a62ec4e2a4eb570f93c6fcedd80ad5685e0f9d6866e8cfbbb84/websockets-17.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:26838e2d95d7004c52e8c7b6b51676c872093a3b55a497824f899116a15a8a55", size = 226472, upload-time = "2026-10-19T16:55:35.484Z" }, - { url = "https://files.pythonhosted.org/packages/36/5d/3a6d74e409f24ae4e8661a9d74d6645f71b3e91425a527c0e3f2e78bb15b/websockets-17.3-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:508775efa11d26aec186d10154359f52276e2baf9ca201b52356330883276dfd", size = 223710, upload-time = "2026-10-19T16:55:36.853Z" }, - { url = "https://files.pythonhosted.org/packages/e1/90/e08eb5d69b73cf5babf80922a8c964019b48339ce5c694a5d0c0f083c5a8/websockets-17.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:2789d203babb6ceb2770aadc2394c1f99263ec37fba57a93064f9a8ad899e8ff", size = 226532, upload-time = "2026-10-19T16:55:38.191Z" }, - { url = "https://files.pythonhosted.org/packages/c2/45/b1916efa1dad5af33beafe5c536810e1c80856b7e913f671c35031c57745/websockets-17.3-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:cfef7f7aa434a1e632e0ebda14b39f4f1d7975e0fce5c77ea7b43156fabf9bd8", size = 225129, upload-time = "2026-10-19T16:55:39.635Z" }, - { url = "https://files.pythonhosted.org/packages/04/c1/d427abb3f11e92f102f70f8e73addb767fc62c614565c0ee3f5657fa3551/websockets-17.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:39f532fa0d9026de4b9315a175998646112776baad54d55348435c11b05d034e", size = 225900, upload-time = "2026-10-19T16:55:41.033Z" }, - { url = "https://files.pythonhosted.org/packages/07/2b/462fab8e4b09eaa4eac2f40fcff8ee30f851aa40fb518efb0177262f6590/websockets-17.3-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:85d6daa3a7ca404570ae130babbeb347ef9d3faca5300fb13cfa4bb48c3d30d1", size = 227007, upload-time = "2026-10-19T16:55:42.314Z" }, - { url = "https://files.pythonhosted.org/packages/71/36/7404a4376021a0cc7ae9fcbdb1196c0c8aa48df4fd370c185f4f5b677bff/websockets-17.3-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:ce39283ef08b0f28478e920d4d89a1fc169176e568e8a6a821332673145522eb", size = 224565, upload-time = "2026-10-19T16:55:43.93Z" }, - { url = "https://files.pythonhosted.org/packages/c9/5f/b8ada5787d11e6edbf58e2d680235fb3b2fb3298991cc310566f4d6c2fbf/websockets-17.3-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:23046098ebf844753cfd211033624a8247520e5bf2194c24cb1a8c222917acff", size = 225516, upload-time = "2026-10-19T16:55:45.398Z" }, - { url = "https://files.pythonhosted.org/packages/23/1c/0533f760237ac6604efd0bf98c18ea4c1381f2cadd8c8d0b05faecb07a80/websockets-17.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:724224d4c457207271239114bf43afafc3eca4a1b4661ccdd428d11869a03bbd", size = 225797, upload-time = "2026-10-19T16:55:46.989Z" }, - { url = "https://files.pythonhosted.org/packages/97/b4/0e580e8f96197130ebdb32b727e9c891594c930be30d8a9de9aa0bbb7e2c/websockets-17.3-cp313-cp313-win32.whl", hash = "sha256:5af7070d80d278832cbca9c3c3dd44b30a26dcfa3ae1e0f6f19ff34edc27b689", size = 218712, upload-time = "2026-10-19T16:55:48.379Z" }, - { url = "https://files.pythonhosted.org/packages/7d/6c/db5c907d1cbea84444bc759ff63db97fc586988d11a34d5565e8b50080fa/websockets-17.3-cp313-cp313-win_amd64.whl", hash = "sha256:66027e401c70d0cf55021b91b8a7ec2cd5810e20602f945b4fe6ae8b37ed232b", size = 219026, upload-time = "2026-10-19T16:55:50.688Z" }, - { url = "https://files.pythonhosted.org/packages/f1/d3/30f04bec5b9cf0c00c98c038494b210ece923a0b05b6df38a162b759e5ed/websockets-17.3-cp313-cp313-win_arm64.whl", hash = "sha256:6b14914e67044724c31a9360c7b89e9d070117c630746eefdc1620d967545acd", size = 218958, upload-time = "2026-10-19T16:55:52.085Z" }, - { url = "https://files.pythonhosted.org/packages/27/ad/f65e365bbf38d61164b0c2f64776fc7714bfa59ac51e492b038a35f4ab1b/websockets-17.3-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:bc8fd230ef013951900c1fda100eebe4a4b1b407dde2a44186995042dda2c628", size = 218288, upload-time = "2026-10-19T16:55:53.387Z" }, - { url = "https://files.pythonhosted.org/packages/48/1c/33271eba53b4927a1b91d99d838a6d7b888e6f708425262c911450d73696/websockets-17.3-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:cdb8e4b0f6a41b857c74c03116e8ffbef59ef8e533e934b532843178990d01d5", size = 215977, upload-time = "2026-10-19T16:55:55.063Z" }, - { url = "https://files.pythonhosted.org/packages/3d/f3/6d982c60f6c7c95e5faed53d39263df273ecfda904c7d6920c37eee58dd1/websockets-17.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:018fab26140ce221c3853454a608e4e7004f4f10641cb97819dcd5b917bb2e99", size = 216193, upload-time = "2026-10-19T16:55:56.424Z" }, - { url = "https://files.pythonhosted.org/packages/ff/c6/4ff6b8d2a4b32719d4658bbd791ee9d19939a47a69b961c961fd9dc3a64c/websockets-17.3-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:dd0f3037d501178a761fd2814370aca547f79e99a200a61a1f6e7b79ec3d78b9", size = 225573, upload-time = "2026-10-19T16:55:58.252Z" }, - { url = "https://files.pythonhosted.org/packages/eb/8f/46e4030947f5590cb61832901f44a3edb07ef8d1e27f6c06b42c5f1c4d33/websockets-17.3-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8dbb3862aa649de95660b6337d97101977f160b5b354d07b82fe309874d2c8bc", size = 225927, upload-time = "2026-10-19T16:55:59.561Z" }, - { url = "https://files.pythonhosted.org/packages/f0/1b/3db30fdf4fbefa4ac463060d3f87e2d444f960aa1234028468c09b88bffc/websockets-17.3-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af37a1e6b6bd506b597d5fb4cf111fb527d1b2223608a5d441d4738827cfd166", size = 227169, upload-time = "2026-10-19T16:56:01.029Z" }, - { url = "https://files.pythonhosted.org/packages/02/ed/849799cfc0e3e359b75ca1d50605376da52dc9ef0b2a53931e3f5991f96e/websockets-17.3-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:740bba4223fa5216d4d6c5dcd29e697f37229b8a61b69e1a50527b0ea993ab2c", size = 228542, upload-time = "2026-10-19T16:56:02.377Z" }, - { url = "https://files.pythonhosted.org/packages/19/53/dcc397e20ce792fffd9a8f79b6333275748ee7a23f807e576166a0b16edd/websockets-17.3-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4170556762c6fd2913d99dfdd8dbb4c927584899df7facb1034627e355263c45", size = 227772, upload-time = "2026-10-19T16:56:03.768Z" }, - { url = "https://files.pythonhosted.org/packages/c9/36/e5935782f71e9e22247b2a2e562da05e18d8945c49f2692ca1bdaceec178/websockets-17.3-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d355b22270be8062360b9df2ee0b10277590789a1059257916fb9e256a0cff80", size = 226518, upload-time = "2026-10-19T16:56:05.332Z" }, - { url = "https://files.pythonhosted.org/packages/27/76/bd5978a1e403fc646230cf35cf7c06b40b3a232d440881b9e89ede229b18/websockets-17.3-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4aa85b34c21cf97b3470793d0bf0763d32bfd1e67b83067a0a3ba8dc3474dacf", size = 223766, upload-time = "2026-10-19T16:56:06.703Z" }, - { url = "https://files.pythonhosted.org/packages/da/87/c66eb39bd851d5c14d9eb75aa64d03cfcf2ded77927ca067b5917291d19d/websockets-17.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:a0e2e7c2c1a4f25db7b6596738d810c10732e77f852247300a1bc49e364d6dc9", size = 226644, upload-time = "2026-10-19T16:56:08.198Z" }, - { url = "https://files.pythonhosted.org/packages/fe/ae/b9a31d5497fa0b73629a097b173a26123da2ed656b562114644bc623414b/websockets-17.3-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:7fa69212ea60ea24e2d8aff23fe102b1f87f1b27a320f92d2e7b3468997a496a", size = 225107, upload-time = "2026-10-19T16:56:09.627Z" }, - { url = "https://files.pythonhosted.org/packages/61/0c/b773a102f84b60b2052b2cfde773d2f3cd3e8eaa93a145f54450460549cf/websockets-17.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:80a6e37e235780f189558ab804f3cbc01c18f5c578995739b49613d544d34ebf", size = 225891, upload-time = "2026-10-19T16:56:10.973Z" }, - { url = "https://files.pythonhosted.org/packages/b2/fa/e7e538575dd4912dea9ea4c9ae86519aa1420969d9cb5cf02fd10fd20ba7/websockets-17.3-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:628efe13630ac3397e7d1278b6be6f22f37a86d638a324334b4cd43c1daf9928", size = 227064, upload-time = "2026-10-19T16:56:12.295Z" }, - { url = "https://files.pythonhosted.org/packages/28/87/bf2b928c156deefd0c50285a48fc985e2ca85d284e7d9981cc5b79b0e696/websockets-17.3-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:443fa28652682d2a3ec3eca49af1b87cb2523561257683e62e03a98967b22138", size = 224618, upload-time = "2026-10-19T16:56:13.73Z" }, - { url = "https://files.pythonhosted.org/packages/8c/9a/d59817ba3535f787c1cf8990a01b3d2896a7d9d8f3b5d55bed22fce595a6/websockets-17.3-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:6705af9d1005127302c04d9f1533ba56e289336c465923ef878430e99295a0b9", size = 225571, upload-time = "2026-10-19T16:56:15.199Z" }, - { url = "https://files.pythonhosted.org/packages/a6/96/8210379dac889e16c75099aefffa200dc55dc8cb030010f309a7eb9c75c1/websockets-17.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9bde5d82d7ac4859e0cb3a35e148f537a8d4e56aa43f42582b5f263982f095ae", size = 225869, upload-time = "2026-10-19T16:56:16.569Z" }, - { url = "https://files.pythonhosted.org/packages/97/0b/d4741c977fec9e6482beffece572d544d42d230f56fc3ef504f96521063a/websockets-17.3-cp314-cp314-win32.whl", hash = "sha256:be7be57097a65a8fab3d0f0a10d12931deb626a7d8082eb732b1ae41f3a202e3", size = 218232, upload-time = "2026-10-19T16:56:18.028Z" }, - { url = "https://files.pythonhosted.org/packages/33/69/2f9ce899776d0c522f7f44080cad4228a1c14ec13b0125a2efc12ebe41c9/websockets-17.3-cp314-cp314-win_amd64.whl", hash = "sha256:2b06213c8e1ce93b18d0476d7a5e647436c8f23d099888c9065e930e80f4bed5", size = 218582, upload-time = "2026-10-19T16:56:19.399Z" }, - { url = "https://files.pythonhosted.org/packages/4e/e9/11b885666d72add674440a3435c059bea325616959cec8be42605948714c/websockets-17.3-cp314-cp314-win_arm64.whl", hash = "sha256:6b7b540bb321f7f0a7b8f5d107f941bb361e3a154c0b594dae0394997b91b743", size = 218465, upload-time = "2026-10-19T16:56:21.005Z" }, - { url = "https://files.pythonhosted.org/packages/c4/0e/0c0f40ab8eefe9d5a6c78b4e267d8e37d70d3db8dd195574e0ab867e4f81/websockets-17.3-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:c9d06edfd974e918b40e0662a7e76dac13125529ee5ec9fbe42dc0d6faa209c3", size = 218614, upload-time = "2026-10-19T16:56:22.457Z" }, - { url = "https://files.pythonhosted.org/packages/1f/93/d22b3d63aa439bc01a9477880070d05e0b257b0548294786a33be3e842ec/websockets-17.3-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:0a0bcf66289b9d017c175562c35c5304b5cc3ed56aded994ae30b0a9654ba405", size = 216151, upload-time = "2026-10-19T16:56:23.95Z" }, - { url = "https://files.pythonhosted.org/packages/b9/92/f60a9672cdeb8cb4f7156e6e83c76d59fdc586737a97ac77129e9fc188a2/websockets-17.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f3ed747b7651668131029c720fbc32c7ee2d129bdad200e6c8f4037b20f7913a", size = 216354, upload-time = "2026-10-19T16:56:25.251Z" }, - { url = "https://files.pythonhosted.org/packages/9d/da/2be8c5f3c6612d4523f95b074e2352bc11bd090cf121d32bc11af1d52e70/websockets-17.3-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:5868a02c4f6d698ddd19b4c9742748c03dec045289915806845189d96bc3d314", size = 225937, upload-time = "2026-10-19T16:56:26.726Z" }, - { url = "https://files.pythonhosted.org/packages/85/1c/cb84aec871840acd66dfa84520bf7b8e48ce70bdb3f4baa4efd097fbe6b1/websockets-17.3-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fa87ea2ad64e59fe5622c1dc5716106b6d6e7e4b26b848cb5f5710a75c292ef5", size = 226215, upload-time = "2026-10-19T16:56:28.1Z" }, - { url = "https://files.pythonhosted.org/packages/9b/7b/cfb65557accec2eda2c80288e13eca6f1c797c579375906eb73f4053cfd1/websockets-17.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:65e937576141ac50fac32fa9736dbb3e0e4a7769f91be004011a09216c6ab05f", size = 227389, upload-time = "2026-10-19T16:56:29.518Z" }, - { url = "https://files.pythonhosted.org/packages/70/a3/7e08ec4b23e376ed228831aa44b2f2a3f2e7025cc66dda4b2e53dcc2619e/websockets-17.3-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:35381b575f70a08d4241e73c0cde4672bb9b2a9aae8767ca6b7fb61305a052c8", size = 229534, upload-time = "2026-10-19T16:56:31.072Z" }, - { url = "https://files.pythonhosted.org/packages/4b/7d/8a813e3e53956f876cfaad4f6358625bbd94168aa8046c44e2f3561f12af/websockets-17.3-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5142798871a248b422f353e0684d51dfa119de3403a6fa0904b7cb806d9790ce", size = 227959, upload-time = "2026-10-19T16:56:32.656Z" }, - { url = "https://files.pythonhosted.org/packages/41/23/5f3dab6ab44f2f30042db83a658a57129d5e3c0425c798b3c3e727bc060a/websockets-17.3-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:e164c4a6868d11988c7f2386e3278ccff21c665cd7d08279b62709dd37a3167c", size = 226691, upload-time = "2026-10-19T16:56:34.101Z" }, - { url = "https://files.pythonhosted.org/packages/5b/49/99a3fb5a2e94d677fbd0d014a6f9a56a3d2b8e8007b7175727bc4fc4ae94/websockets-17.3-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:10b24e836ee0233ca078e1244f6ba40343a22127a9a736f46a7e7b18de2cc711", size = 224225, upload-time = "2026-10-19T16:56:35.452Z" }, - { url = "https://files.pythonhosted.org/packages/6f/e5/f503a4d757858d083c90ea85dd1fd636ae9eb63c9552c75a4c38514ee7ed/websockets-17.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:56a76556ab04ab54a675acce2cac8b4e74ea2cec558a7c9ed37e0367b04b5d50", size = 226984, upload-time = "2026-10-19T16:56:36.887Z" }, - { url = "https://files.pythonhosted.org/packages/4a/a6/8586844ad4b21988837624e1f4b331bc71919c85a6eb1ee3c8bd29893f27/websockets-17.3-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:33221e49be79d7bfe6d12bc52ef9458b256ab74fa8ac5660acfa3065de1c7870", size = 225436, upload-time = "2026-10-19T16:56:38.213Z" }, - { url = "https://files.pythonhosted.org/packages/a7/b9/f419506494d6ffd205a9c3258f56ff5aeae6976de26361057de74f4ab659/websockets-17.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:2fa79b9a48ae59744316c71a34cb9f76f30c93e117338522c5135cb7eac10351", size = 226325, upload-time = "2026-10-19T16:56:39.606Z" }, - { url = "https://files.pythonhosted.org/packages/28/c5/55a58faa67149e84cb98b33f9d8fda95242677ea07b78f3ecaf2e77877d6/websockets-17.3-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:f87f02afe05c1c246012e3de100a77cfbabd17db709fe93cf074271ab239b312", size = 227342, upload-time = "2026-10-19T16:56:41.041Z" }, - { url = "https://files.pythonhosted.org/packages/35/e0/fbe561dff24b6ef1b2034877f37b56eb9b81b3c103e2a8b03819bf2b3b6d/websockets-17.3-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:8135a549e27e9941a70e2d2156676ef2ffeff4b06e9d564dbaaae963482afdef", size = 225036, upload-time = "2026-10-19T16:56:42.433Z" }, - { url = "https://files.pythonhosted.org/packages/0d/37/d80753064f8370a24d3bec74807c3928d7b0ebef5381956e2a0108b365c2/websockets-17.3-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:ace8dd1efa5f44c482d091aa38322e20e3ffe5adcdba6b67ad9f4e7da58f3f68", size = 225807, upload-time = "2026-10-19T16:56:43.774Z" }, - { url = "https://files.pythonhosted.org/packages/f1/9d/a11d3168522a2959c4a5661728744d62b9eee344abdba5f9fbc1d359742f/websockets-17.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2129c9a5fc05a230ce088745a790af073e582b584badc7b05db067ee326f56d7", size = 226241, upload-time = "2026-10-19T16:56:45.088Z" }, - { url = "https://files.pythonhosted.org/packages/06/28/16107b3b83fd2b5024bfecf8d000140f555204a0191202f9c4c981137810/websockets-17.3-cp314-cp314t-win32.whl", hash = "sha256:af7c474f0d8f4d2a196370e85033873c7b063a0b5da9a4f143aa023e3bd25407", size = 218365, upload-time = "2026-10-19T16:56:46.41Z" }, - { url = "https://files.pythonhosted.org/packages/77/dd/8b00e1dd552788d8c7762d7ef61de8f2f238d7357b1a02d4c4650b112196/websockets-17.3-cp314-cp314t-win_amd64.whl", hash = "sha256:0c63ad657695e8f1a48624754cb6b464118ac50d4c1d477c26461c98390f0a62", size = 218706, upload-time = "2026-10-19T16:56:47.754Z" }, - { url = "https://files.pythonhosted.org/packages/39/eb/5d90d57a5cbe614b2f13433aaf1c0b068c804589379061ba06812a185a89/websockets-17.3-cp314-cp314t-win_arm64.whl", hash = "sha256:3c4f631dc8d00e470cde3ec0a35d4b58a817bea592411956f1cf4099dbb306b3", size = 218622, upload-time = "2026-10-19T16:56:49.07Z" }, - { url = "https://files.pythonhosted.org/packages/6e/41/1efe5ecae1f32495dc75641704f959bd2d8e56cdc825f3acc5e010a51960/websockets-17.3-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:f300f28dff74ff4148c21e6971e4de6ca0c34e0086a3d95c017c5174ebf85ca5", size = 218211, upload-time = "2026-10-19T16:56:50.423Z" }, - { url = "https://files.pythonhosted.org/packages/01/ec/4edb653533241203db3f11522e122338d4fda50a41ce2a542029086f8eda/websockets-17.3-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:32029441af953e980b9940f042b337fe4ad9a97fa8b17a4ed878ec67b5b89ef4", size = 215944, upload-time = "2026-10-19T16:56:51.766Z" }, - { url = "https://files.pythonhosted.org/packages/d5/b9/ec450b9650925dd5cf27c1f36d0464786fe3ac702ed656879c4c0dd5c4df/websockets-17.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:09f007b2150eff015b2109f006e2ac2012d376f41486defa88ae78a776b00cff", size = 216164, upload-time = "2026-10-19T16:56:53.125Z" }, - { url = "https://files.pythonhosted.org/packages/15/1e/63f7fbff9f0540a0331f1a62424c9ff24faa6ba8aec264f55e9e31017eea/websockets-17.3-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7bdc658c9474864893e0b6b94f1390bf6a912952df1870dd93bb7d1a902b5628", size = 225608, upload-time = "2026-10-19T16:56:54.442Z" }, - { url = "https://files.pythonhosted.org/packages/0c/1b/f6679ad61cb8c110033a1b30d561d5c1052983e202157251ff1778f27932/websockets-17.3-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:15decc0fe293d9e3f924bd483f3d76f3d0ff26845112a470e3f8842fec2c82a1", size = 226042, upload-time = "2026-10-19T16:56:55.727Z" }, - { url = "https://files.pythonhosted.org/packages/28/c6/ed993aaef8046cbbb939ae367ee3dd5383dbd055f0500a5b8aed101168b6/websockets-17.3-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:997617dd7856c5dad742bf6893b872319156dd43f47587541a59e4a852d52bbc", size = 227203, upload-time = "2026-10-19T16:56:57.076Z" }, - { url = "https://files.pythonhosted.org/packages/aa/96/7057dc71affe6c8252df8648f5a225642228a6fdd8d046a6b9aa1fb0e9eb/websockets-17.3-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a004c1fe5a72c496f28c6c1d8c2dc5cfe3278d99478e18f8b838c70a912b366f", size = 228900, upload-time = "2026-10-19T16:56:58.633Z" }, - { url = "https://files.pythonhosted.org/packages/43/e3/8b3268bb7e72b465e55172b86d55f58aa277fb6d9bac92aee615345874df/websockets-17.3-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:35fe35d20baa661cef4a12ee7bc42eaf2376d43ef9816ab29dd47ca957f7a73a", size = 227684, upload-time = "2026-10-19T16:56:59.975Z" }, - { url = "https://files.pythonhosted.org/packages/59/15/fa31c0a12240b1225c3712ff080d2f7ede4f695ca90e59fdb58e8affabba/websockets-17.3-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8b3bede7d583bc9f47d8693a29984882e59077db1a5238ad977fc70ae8169741", size = 226580, upload-time = "2026-10-19T16:57:01.371Z" }, - { url = "https://files.pythonhosted.org/packages/22/b5/75d911c206a3035e2ecfad107878e62c06e574b2437fa2cfb4ecef436fa3/websockets-17.3-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dafbb58a149d1ebd5767b3f064f911c5ee0897608005e51c3904b0ada2a8d99c", size = 223967, upload-time = "2026-10-19T16:57:02.839Z" }, - { url = "https://files.pythonhosted.org/packages/0e/f8/f98aa36f611acd5770819f6690125c20d55f221fd6db8d00d284b5f78e89/websockets-17.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:80326bc571164bbbb6bead2e35d0c943b23b24fde629032197c58151529d24d8", size = 226689, upload-time = "2026-10-19T16:57:04.458Z" }, - { url = "https://files.pythonhosted.org/packages/1a/36/d52f5dff7597de6fbfc26c3d126abd668137915719aebf97abcc3be77eca/websockets-17.3-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:7d53fc4b90ef6e11de639dc18744d9be8cbd70ccb5ce80027aaffe7b1ab0215a", size = 225353, upload-time = "2026-10-19T16:57:05.857Z" }, - { url = "https://files.pythonhosted.org/packages/d4/10/dcd70ad9f9cd20e8af43284ac250af610e8bf9022da25f5b409153d033b4/websockets-17.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:fdd00937f15f5f93c8e53d8060a8c4c010431ab595a9b5b50ddd569a04603944", size = 225879, upload-time = "2026-10-19T16:57:07.249Z" }, - { url = "https://files.pythonhosted.org/packages/70/ab/f26c6bfa99d38ca3d1bf23145306d97c5d0c75e133a8d837373e4b3d4629/websockets-17.3-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:1dae5cd6c92d4440b15f20aa2987baa73c47ea14baa0fec8536a542e82e0ab33", size = 227031, upload-time = "2026-10-19T16:57:08.817Z" }, - { url = "https://files.pythonhosted.org/packages/d7/3f/c8fd74cdb526cc65295b7468f2f84ba16678646d8174288822f99f510274/websockets-17.3-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:b225c656efa2dedecc81651d2290170af25887b7de4f38c5efc7c5ae2b9442ab", size = 224842, upload-time = "2026-10-19T16:57:10.298Z" }, - { url = "https://files.pythonhosted.org/packages/c4/c5/b3a07ce1c54fc0f5441642f5352662b90d7e658c966730eaf6d78a5f20bc/websockets-17.3-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:bd645b5d2f810a181c44f4a71135e7c365b44f4be9ed3d1892635be13a857553", size = 225744, upload-time = "2026-10-19T16:57:11.615Z" }, - { url = "https://files.pythonhosted.org/packages/66/37/8321a8a6ab0215d4df0238e49ace5f539364cf337bb122b85c788e8c93ec/websockets-17.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:d2605a3b2af8d66f8b75312d223642c065ec773446c04566d9030ad5e2db13c9", size = 226006, upload-time = "2026-10-19T16:57:13.049Z" }, - { url = "https://files.pythonhosted.org/packages/f8/04/8c457a7e6a260b673bf4e6f2f422eb4af5f11c48505748359706f24f1bef/websockets-17.3-cp315-cp315-win32.whl", hash = "sha256:82e60c00cfb8493a5ba27cdf9b3695fdd153f666f73e11f18968f78ead1d8705", size = 218196, upload-time = "2026-10-19T16:57:14.41Z" }, - { url = "https://files.pythonhosted.org/packages/a0/7c/c2df129d9e344b99bb388bcac54fbbdfeec29e6c716c12dc9a3398757940/websockets-17.3-cp315-cp315-win_amd64.whl", hash = "sha256:4d5f2492cb2192aab2d42e57f2caa2159b4fd20fde06f859ec13354f524b176c", size = 218490, upload-time = "2026-10-19T16:57:16.234Z" }, - { url = "https://files.pythonhosted.org/packages/e6/4f/721b778c85559b2949e46246838e31a346dd815b3cdd8460fe517235675a/websockets-17.3-cp315-cp315-win_arm64.whl", hash = "sha256:55494475206113dbaf731dc8c5ffd5e1094175b753b7bbaad09fe3d7df61165c", size = 218403, upload-time = "2026-10-19T16:57:17.631Z" }, - { url = "https://files.pythonhosted.org/packages/b3/28/241d9ebb4dad79346b5a6abf9f14d7685b12ca358d250eea4920cdb1caf3/websockets-17.3-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:23cb6f6d64e3a389bb8ba150f947f9a6c8c0aca383e814ca3c5cffab738d5646", size = 218523, upload-time = "2026-10-19T16:57:18.978Z" }, - { url = "https://files.pythonhosted.org/packages/b0/bb/559fe539992102c66cbca38b488af6c7b184ab7736d819afc0f72268a2b4/websockets-17.3-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:f27e7e8a85512b6a4b490d5756edde8e6772883a5800e1476172e44eda3f7d7c", size = 216103, upload-time = "2026-10-19T16:57:20.412Z" }, - { url = "https://files.pythonhosted.org/packages/34/ee/e8ade4f13a3d0da68636fe44bb8ac1a3e36fc57070512788320dead42067/websockets-17.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:6342f79d6f50e680c8aa59e0615d745e867e51ffd59c77093be60b7c433067af", size = 216316, upload-time = "2026-10-19T16:57:21.761Z" }, - { url = "https://files.pythonhosted.org/packages/4d/06/4812b2a7a5e6571d9be425e76cf54ee69aaa15720caa02307785aa5b19a7/websockets-17.3-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:fc23e72bd7f8a8e540fed2244524d0a9aeb6ae3325f3d56f04a7a3debe5b04c2", size = 226467, upload-time = "2026-10-19T16:57:23.077Z" }, - { url = "https://files.pythonhosted.org/packages/d3/e8/adfc05d7f9b6b0cce6cc554426c50b7058609119b6b84a39171fe5ed4e50/websockets-17.3-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:722ab747ff5dc28070b1a8c020dba6466f13f2ab56bc251ad301fefa2454aa1e", size = 226736, upload-time = "2026-10-19T16:57:24.419Z" }, - { url = "https://files.pythonhosted.org/packages/96/b2/d5b93dd933552554507edae9e3a4890269a8ea8b46019450ea9c8a30e7cc/websockets-17.3-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0d20d6ea5aabbeba2e054d33e405192ef75dc12947bbd00ec97d23b14969d325", size = 228065, upload-time = "2026-10-19T16:57:25.908Z" }, - { url = "https://files.pythonhosted.org/packages/10/37/642f0f1cf1c4814147a4f0586f796a0b38e42b69e5a296bfc270fb660051/websockets-17.3-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:90cc9973c51811918247a78d9ab2f54871296e4e37e69a98aba4d3c9acedbf62", size = 229692, upload-time = "2026-10-19T16:57:27.63Z" }, - { url = "https://files.pythonhosted.org/packages/5b/33/eac81cf62ac394b61db6a27ccbe8fb9ae382016ef73ede1edf9242a6a43e/websockets-17.3-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:63b87c93e28957e6dc2bb92d31727a863c9bf4a4daa080f0995fdcb0242c9166", size = 228503, upload-time = "2026-10-19T16:57:29.031Z" }, - { url = "https://files.pythonhosted.org/packages/0d/84/e057788a9bd056f4f7d3a06b59efaaf724bbc6f2d1e1d316f8a93c951abc/websockets-17.3-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f7431e71072962d3ed1768038200aa4f1e76d9c2d7bedd554d57a55faaf6644", size = 227379, upload-time = "2026-10-19T16:57:30.571Z" }, - { url = "https://files.pythonhosted.org/packages/fa/a7/cca1f9f45b893bb5b7545f2b234f910e07fcd2f8065724ac1a62a0961be2/websockets-17.3-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:534ed583fd4323de45d196535a444cebd1af2105e6e4e0cdcbf8cea266a8747a", size = 224719, upload-time = "2026-10-19T16:57:31.895Z" }, - { url = "https://files.pythonhosted.org/packages/1f/a0/5d07451027150c802ce4c9999e86994a3f0de5f4dbe3d1cce46995999269/websockets-17.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8879b6a4040ee925c638548238ab7fe612cf5fa8752fe847346da0da8be81c3f", size = 227564, upload-time = "2026-10-19T16:57:33.236Z" }, - { url = "https://files.pythonhosted.org/packages/62/90/835f37e13fac0c615a700caae0d39deff1de2d2b9b341836a786f9b359e0/websockets-17.3-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:58e5d1e935a90878a935c7d2737a25c71cf4f1c13b6e6bef454ab722c4f338bb", size = 226218, upload-time = "2026-10-19T16:57:34.876Z" }, - { url = "https://files.pythonhosted.org/packages/16/8a/718639939b947fe715501e8073350fd3f8a42f8b5eba3c0c2389c5836513/websockets-17.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:0a657b51e4a5f4ac577c11e706ff9a884ea5aaf3e2666bae283a251c63e66acb", size = 226712, upload-time = "2026-10-19T16:57:36.248Z" }, - { url = "https://files.pythonhosted.org/packages/e8/45/6bef8572b9b0dee51369b69776af1e4c7cc3a807f199dc3c165bbcf1199a/websockets-17.3-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:411aa0fb234f42a1444dea1e177890ddfc577b36ffdfafec25cb0d2c818e1af8", size = 227819, upload-time = "2026-10-19T16:57:37.586Z" }, - { url = "https://files.pythonhosted.org/packages/f1/3f/3b726d0b46a132e641d2d8c0243ea8a7d39464dbaf28c7a206e51fbae681/websockets-17.3-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:623d4b44f64efdf235b1e8dce266057073d93cde6197e7d7684f20c297f67f30", size = 225573, upload-time = "2026-10-19T16:57:39.285Z" }, - { url = "https://files.pythonhosted.org/packages/90/96/cd972a12e1412d9b42c42ef42efbd81aa396ca9408d982d524012f011a8d/websockets-17.3-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:5d0c871efc696ef5eb8514df64b86ab28736db753ebb42a2101f3b562f4849c0", size = 226430, upload-time = "2026-10-19T16:57:40.915Z" }, - { url = "https://files.pythonhosted.org/packages/7d/2d/e11524771588188a39f6da234779d4942496b96c5a10b92f3df30db48608/websockets-17.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1db2604e6aedb7a2cb2f6e0575d6c9a852ccac8239703a930ac83b63309177a5", size = 226728, upload-time = "2026-10-19T16:57:42.245Z" }, - { url = "https://files.pythonhosted.org/packages/17/9b/63722aed973f53ea579e1ce0c4563a2b8b536629e556feff26e4c6a2a60d/websockets-17.3-cp315-cp315t-win32.whl", hash = "sha256:07246d4f0293ef0b87eff3d7dd88c1f03dd9f678fa39f6de87b2af8504e7e0de", size = 218325, upload-time = "2026-10-19T16:57:43.585Z" }, - { url = "https://files.pythonhosted.org/packages/34/07/5e0c92e225546f1789c957c0383852797be7c899b07207e9b6eb4a93473f/websockets-17.3-cp315-cp315t-win_amd64.whl", hash = "sha256:856bbb24f2ee6436af7609267e73309e4bb0a0f9982f79f1c2e01019279c6671", size = 218641, upload-time = "2026-10-19T16:57:44.918Z" }, - { url = "https://files.pythonhosted.org/packages/d4/e4/339663de65c44ab3eb5209890e86eed26e1a131d6afab3df6f1c3e5b4d8c/websockets-17.3-cp315-cp315t-win_arm64.whl", hash = "sha256:a22c4956a4d858200dba83f0691bb692d77b0eeddfca80157820d20b85dea4f1", size = 218564, upload-time = "2026-10-19T16:57:46.332Z" }, - { url = "https://files.pythonhosted.org/packages/e1/f1/b462b1518779adf0b6fce305beee07357a79cf0724bbe61113ed6521882e/websockets-17.3-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:34c78052277053bcb09810ac8e9ba4029f9e3e277833fc18ec1c928a6246ac91", size = 215839, upload-time = "2026-10-19T16:57:47.742Z" }, - { url = "https://files.pythonhosted.org/packages/a9/59/7dcea408892967516cc00d491ee7bba48577059c6eb0811f436b720bcd98/websockets-17.3-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:ef07e0b6b879f699a16fc7a513b974246fdeaef44908a021130cf4afe6a1c89c", size = 216114, upload-time = "2026-10-19T16:57:49.111Z" }, - { url = "https://files.pythonhosted.org/packages/c6/b7/2d447e461f1160dc8dcdd8b143e2adba54d402e5f828eeb1f8469970c937/websockets-17.3-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:99c5637b74e2805ee4de9e2a43c8b45f678e50abb1c2da9880f0372f6498ba2f", size = 217065, upload-time = "2026-10-19T16:57:50.424Z" }, - { url = "https://files.pythonhosted.org/packages/01/51/35aa5edd12b23e0001b85517ad447342c07a29fcee62009b0859825b77a7/websockets-17.3-pp311-pypy311_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2c460aeb12c2bd1c204944d9e9199595bf9e505eb542018d304bf9e63cb60cad", size = 216952, upload-time = "2026-10-19T16:57:51.72Z" }, - { url = "https://files.pythonhosted.org/packages/6c/db/537306b92236d761b99dc56a7316c0ad46f2854cd0756585b3a9d3fe5639/websockets-17.3-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5e1c174b366565e101f903f9d1cc96d5508f805759dd37d012743f1c73ec0d7b", size = 217844, upload-time = "2026-10-19T16:57:53.144Z" }, - { url = "https://files.pythonhosted.org/packages/e0/c2/494bed87536f3822872e57b07ac9afa744af88ff64dda664b9caa32b1a72/websockets-17.3-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:c4b3f2c7d84f303da873b634d0beef83b5e1137294c3de4e23102841dac0cf4a", size = 306274, upload-time = "2026-10-19T16:57:54.525Z" }, - { url = "https://files.pythonhosted.org/packages/5a/1a/5582103e0362f86c4725051ded89e585ceaf750f26beace530b7e42c81c0/websockets-17.3-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:0e65260a1b1d7b81651f47343d836de70b88b02358ae3658efa6382104ec37b1", size = 215872, upload-time = "2026-10-19T16:57:55.95Z" }, - { url = "https://files.pythonhosted.org/packages/ef/a7/f69d65ed3ff9ae73d428a918300c23a992e4d50683090b8dc33cc3341d5a/websockets-17.3-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:94c02b0702656f083c098bdbd93bce22a7aa7a2b34ba56d2472efb67dab7cf58", size = 216136, upload-time = "2026-10-19T16:57:57.251Z" }, - { url = "https://files.pythonhosted.org/packages/69/76/c64fda4ac18a3aeb32e66acec481011a766add480b6362fad80e2c3c1963/websockets-17.3-pp312-pypy312_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:ade76f8c84ade325bbed96806357fffd353fcc29a5166d6dc6d39381f6d9f76c", size = 217080, upload-time = "2026-10-19T16:57:58.593Z" }, - { url = "https://files.pythonhosted.org/packages/6b/6d/085a3f0e6152bbe79917973f3d33cd008437de6c04675e2f15253b921f21/websockets-17.3-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9a215749c9a88ef2842e880215193e56ae60b856773c99702b078236bc6d4adb", size = 216966, upload-time = "2026-10-19T16:57:59.924Z" }, - { url = "https://files.pythonhosted.org/packages/ed/b8/7eb904583ea2090b329f50487e6f8dc58eb558712b9f3c16f289f0be668e/websockets-17.3-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e7b5d23ef144b32645d97bd99f382c4394c443395f45fe1576786838d26e308", size = 217828, upload-time = "2026-10-19T16:58:01.822Z" }, - { url = "https://files.pythonhosted.org/packages/79/36/f54b4a1cd9456ca0a65a76d77d181621433793aca633dfeed214748ff4f0/websockets-17.3-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:13eace1b315345ebac5b27821f5dcce24e5cf9976ab18f79e00a59bdd67e5d19", size = 306301, upload-time = "2026-10-19T16:58:03.161Z" }, - { url = "https://files.pythonhosted.org/packages/d7/b0/3f01fcb3406662f6deb1e3e72b34dd0979e993991c0b7435a9e12bc14f02/websockets-17.3-py3-none-any.whl", hash = "sha256:dc2b495a92b3971966bf102e73589f950db3ec1ca6713265355ce7771d97b199", size = 212375, upload-time = "2026-10-19T16:58:04.483Z" }, +version = "17.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/79/590c5f0cc7d1661195aeefccb0e342b79f4c77d368d526d028821a390332/websockets-17.4.tar.gz", hash = "sha256:09d3939b70df0c8ad2da145ebd50978bccaee1d565e838b0e7921a34d38571eb", size = 191391, upload-time = "2026-10-30T15:10:35.873Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/d8/2d4ec550208432538d152a41f0c36dc6728cfae0050c6b1442605456d3bd/websockets-17.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:06ea46717553cdd10f2682126cf7a66e91c8ed17b6969f4a95e94b4e01d06188", size = 218746, upload-time = "2026-10-30T15:06:39.361Z" }, + { url = "https://files.pythonhosted.org/packages/56/99/3090fc0e2e343cc7ee60d532b67a2d413830c8fbb0be9ec3bcfbe3371f2e/websockets-17.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:75b32cf33ea40f945f226f97bc1d43151e1a5adff21f420b5e63c468b1a28114", size = 216437, upload-time = "2026-10-30T15:06:41.324Z" }, + { url = "https://files.pythonhosted.org/packages/3c/e9/3d4fb98e5d8aecc7bdbc59c4edf6380fdeddf935445e7f4a205466682991/websockets-17.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b8451f31ae24620cc9372acd2728d87922f2bb0cae3fa57aed68b152844cdf08", size = 216709, upload-time = "2026-10-30T15:06:42.995Z" }, + { url = "https://files.pythonhosted.org/packages/0c/4d/5c7d4f53cc0d7c6f268bbd93865b185e05f65f37f84712a41ab311118f8f/websockets-17.4-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:3b76837cd051d8875913f3934b27205f7a592f78b8a4f4a1f3abc36a2420c5bc", size = 225773, upload-time = "2026-10-30T15:06:44.607Z" }, + { url = "https://files.pythonhosted.org/packages/57/70/80f870701f8610e88649d3cd173a0e7ce66433913da3683035a4370063ad/websockets-17.4-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:cebad8f4796248b91fc2168515e507e5cb6b663a32befd09f3b1e7920acdcb1a", size = 226041, upload-time = "2026-10-30T15:06:46.224Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bc/f2e84b5a933c86d52184814d38b0f9d51fc90fd3205cb7af0d9417ebbff2/websockets-17.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:954d43574f72be244b65f0fa61e2f814214b024f2ec849f487aa2f553f7c6e71", size = 227279, upload-time = "2026-10-30T15:06:47.619Z" }, + { url = "https://files.pythonhosted.org/packages/34/7e/4710475f46afbfe5390b4139556aa4fa0692d3d31878a25a1b26e8a6d78a/websockets-17.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:b529ad6c81ad21db2f4e3d6e33db78ce3b9f272066b438b5d673361f9282898d", size = 230592, upload-time = "2026-10-30T15:06:49.357Z" }, + { url = "https://files.pythonhosted.org/packages/bd/10/cca6dc2316dd8c3b1a62fbf7f8986926ad8c4b2ae3d3be7888059a96b142/websockets-17.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:799c5a23126c9589cb10b6c6b54f9087246940dad20cd74bf3f06fc9ae3bbab5", size = 227837, upload-time = "2026-10-30T15:06:51.015Z" }, + { url = "https://files.pythonhosted.org/packages/68/21/ac1c3d7781d756bd40fbe501890b54a0205b1f0528a559fdcabcede0bd54/websockets-17.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f01a680d4b66fd15cc7513fae55c673cc8cc340d41340305b7f9a782abdbefed", size = 226613, upload-time = "2026-10-30T15:06:52.556Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a0/bd122578f2765fb3714eeef80bd66074e355ff80e0a6de7fefa10de5f36a/websockets-17.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0e51546a3bedadd80dfa5c2efaed840ac51b8632d8db7f9f502175f5349382a9", size = 223893, upload-time = "2026-10-30T15:06:54.106Z" }, + { url = "https://files.pythonhosted.org/packages/51/50/a5214db6b778995b7fe1bfaab6228ba967cb6fd523d4b7af83154aa0ac66/websockets-17.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6686d29eaafddeeab9e48af92103dc0d26161035faa4be083b8b488f1ab47219", size = 226768, upload-time = "2026-10-30T15:06:55.889Z" }, + { url = "https://files.pythonhosted.org/packages/fb/41/5d62d4889ff8a400cf32c8ad35e58b18e92b0e936db0bae785307cd1b105/websockets-17.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:7b23db4b469d9e051ac74d96db9bf61e27c9054de64f8263fefa32bf72867ba1", size = 225358, upload-time = "2026-10-30T15:06:57.706Z" }, + { url = "https://files.pythonhosted.org/packages/b4/94/c344744fad06ae721a6ec69f728a3dd4bd1b94beb7bb64400a8cd0efc644/websockets-17.4-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:0132e3cbd3f5cfc1ec77588961b302d72a02e2603b82c2c23fd5fb59dc4fa206", size = 226125, upload-time = "2026-10-30T15:06:59.125Z" }, + { url = "https://files.pythonhosted.org/packages/0d/00/90d66792bf1ce315fabe18f838eb2090ebad3425139047ed4c4ad354a90c/websockets-17.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:98f16db5e79f2605194c0f899d0532005bb12269e698bf96f62a5635bcf33010", size = 227169, upload-time = "2026-10-30T15:07:00.687Z" }, + { url = "https://files.pythonhosted.org/packages/24/7f/c069129b20504c35bd22abb276a6562e92dccb69c974ca93021a23fb00ce/websockets-17.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:ee48728a07566c32e097d267f4d4d01b85123c9ae748a42da02185b908cbedc4", size = 224750, upload-time = "2026-10-30T15:07:02.077Z" }, + { url = "https://files.pythonhosted.org/packages/4e/3a/0fcb37d6da690aa2512faadb0e9cb5e1043fff659fd415dc8b518883789e/websockets-17.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:2103982762460a764a7ef0021443bb471f46d45ecc6858276e4fe699ebac6b94", size = 225782, upload-time = "2026-10-30T15:07:03.783Z" }, + { url = "https://files.pythonhosted.org/packages/49/61/422745448862b18b8d373347bb73debcd440330f21dd899feac5f920d531/websockets-17.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:648adde345cfd13335342e23cfe94871c7f7f55a43fb254f3b95acb071072968", size = 226021, upload-time = "2026-10-30T15:07:05.237Z" }, + { url = "https://files.pythonhosted.org/packages/96/74/3ea38c6758b497a5d1b7bd953542e9e6446b84aa075a061e9a47e24ceb75/websockets-17.4-cp311-cp311-win32.whl", hash = "sha256:679eef0123861ca381dd8fd9bdc1920e87636ac55eae6cff875c53dcb05fbcf8", size = 219255, upload-time = "2026-10-30T15:07:06.871Z" }, + { url = "https://files.pythonhosted.org/packages/55/66/00ca8b75a634c9fcf70579f9a242b96a7f7a3abeb21a02e2380fff491d2c/websockets-17.4-cp311-cp311-win_amd64.whl", hash = "sha256:e4beaef2f4796558e738e15ca0b8802e35f419a9fa374a978e41706f43c48b26", size = 219556, upload-time = "2026-10-30T15:07:08.538Z" }, + { url = "https://files.pythonhosted.org/packages/4b/7b/c8ccb313439f4803779f186b8133563e6c49c023467a265ae52da7b7e25d/websockets-17.4-cp311-cp311-win_arm64.whl", hash = "sha256:ddab54dc0ec46ed09ef9ac131252cb5740ed21fbe6fc145f3c6fed0b575a8f15", size = 219487, upload-time = "2026-10-30T15:07:09.94Z" }, + { url = "https://files.pythonhosted.org/packages/af/71/b020221345ea6c012dcf7496827a48a744b58696470b2b07fef95a32905a/websockets-17.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3d512e3a6c528c42ce220ed9c3caff83c6fdcd98a1b98249f08ccfc66ad111b1", size = 218779, upload-time = "2026-10-30T15:07:11.522Z" }, + { url = "https://files.pythonhosted.org/packages/8e/84/1c372ae7c032021a84e5c9e9b76b0dddefb354e9b4af783a97efd4d80ab3/websockets-17.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7390e060f830b3d132f484b21ac2783a2d227b682ef62bb8146e1c1b4ca0e45a", size = 216457, upload-time = "2026-10-30T15:07:13Z" }, + { url = "https://files.pythonhosted.org/packages/74/b6/cff249107473f149c6c916a49cba967379fa63b0a7d2dce6896d6848f0a3/websockets-17.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:bcad49104711f88b2b7c3ba166de172857d837248205e541b044a552558fecc3", size = 216726, upload-time = "2026-10-30T15:07:14.468Z" }, + { url = "https://files.pythonhosted.org/packages/77/5d/aff8ecbf1c55c4d96f6dacc46a52102895f58b85bb284c8d325aaf31606a/websockets-17.4-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:cf99debb17227a50620aee16647bb33a0387f5fa5418d628666c0f05745e0d2a", size = 226043, upload-time = "2026-10-30T15:07:15.937Z" }, + { url = "https://files.pythonhosted.org/packages/cb/18/6229d6583031ca81d092a0cd887a13a57b402fb555acc323d39b45967eb7/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9ae1429ee9e52b139167ed0169757806a27ed7307e942e8c62037a9184e9843b", size = 226321, upload-time = "2026-10-30T15:07:17.563Z" }, + { url = "https://files.pythonhosted.org/packages/b8/61/7aba018fd53873e792a25afe1f4c005518133477b727d7455f2f7550c425/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:51adfc30f467077293a6695d8149bcef501c0728386f3a491054f835dadb60b2", size = 227559, upload-time = "2026-10-30T15:07:18.998Z" }, + { url = "https://files.pythonhosted.org/packages/fb/66/37b207df9cdacaa017aa4487f3a9f2fcd668f6f7cfbafdac5b95ea258ee0/websockets-17.4-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c564d1e6531611bf87078c28780456ecc75459dcca189629fff2fe7c020d8e67", size = 230386, upload-time = "2026-10-30T15:07:20.431Z" }, + { url = "https://files.pythonhosted.org/packages/ad/f6/87507e11fbae53817a435945273953b5b020589e309fac4fd60527ee5999/websockets-17.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4c792e6cce24d08f92199d907785c9e64f74c357deeed3dbaf7d699ed5930b64", size = 228193, upload-time = "2026-10-30T15:07:22.112Z" }, + { url = "https://files.pythonhosted.org/packages/2f/3d/90a04f0aa989b68fbd2efcd38237420afe2abe5a1cab0b5d7c2aa4f0dbb6/websockets-17.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c44776f82b04e623eb9e1b81fcd17ac6e9808ae1ba5cdf8edce1f7c869a95a9b", size = 226952, upload-time = "2026-10-30T15:07:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/ad/3e/50952af22b8e3e2d03f7e83f0e335851c6b484c3fd88586626fb1c2a34b3/websockets-17.4-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4d2636a5b61c69e32db0e74b57073dd4a66f1ad195e9398c5f01bba41090deea", size = 224183, upload-time = "2026-10-30T15:07:25.507Z" }, + { url = "https://files.pythonhosted.org/packages/c4/73/2a4a5d9c6bca1127f24af7bf08f406a69052d7f341bc81f08d9e8eb446b4/websockets-17.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:cfbbba4597f19ad717f79fd3f2a67ae7efae647bd6a61e14554e1b5ad242a5bf", size = 226991, upload-time = "2026-10-30T15:07:27.355Z" }, + { url = "https://files.pythonhosted.org/packages/68/de/90d96a579839bfe541ef214315df81d2bd519d952847c303328518ffdd02/websockets-17.4-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:c7b996c02de5e032cb63dc65482b73693b7ecaa586654126be2749ddea239c40", size = 225600, upload-time = "2026-10-30T15:07:28.973Z" }, + { url = "https://files.pythonhosted.org/packages/91/17/12c15ed446d842e40918cd16e79b56ee4422d6fbf210258cb8882f50bbd5/websockets-17.4-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a920e99155d75d1b1c08172da8aaa7200e7b30871fb628d1631d7891a333e30e", size = 226366, upload-time = "2026-10-30T15:07:30.472Z" }, + { url = "https://files.pythonhosted.org/packages/9d/73/cb4c927e806a73a0377696e031ef3c0db409028cdb2373f96ee863e8df8e/websockets-17.4-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:8c00c5c49f80a588a2c4f99d519d2abed4ce26cdca11273041bc8b7e60af60de", size = 227470, upload-time = "2026-10-30T15:07:32.122Z" }, + { url = "https://files.pythonhosted.org/packages/33/b3/e682b3ea069933044f4bf4809eea0cd83e3a5bdbdff601d1777a9ae90795/websockets-17.4-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:52c31d123f5adf14dec694c2a4036bf42c523df7cefc641d31cd05653de56e49", size = 225026, upload-time = "2026-10-30T15:07:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/2d/e9/d039757260705e5a265a31c9fff36b0d4567b842ce2b54e5d14369f200bd/websockets-17.4-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d0acd8191c0e5a61d1c27bfa33b6ec8431982299f5d71c02129aa4f16f182ad0", size = 226007, upload-time = "2026-10-30T15:07:34.954Z" }, + { url = "https://files.pythonhosted.org/packages/db/e7/cb9907fac6f9b28f93beded6efda2953960cd02b633d432acf3451590859/websockets-17.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2a9cb5bbfc33b4ebd3c8d3714d6e09805437f60a14977774e4bd11b5ace46c23", size = 226286, upload-time = "2026-10-30T15:07:36.292Z" }, + { url = "https://files.pythonhosted.org/packages/39/99/85f6f4dd104a5d9a33a1ef272f501d0f2e8527ddf66be1b383d51f90ce56/websockets-17.4-cp312-cp312-win32.whl", hash = "sha256:c63c0d7832956d5f3bb77888b93c854569d13f806289ff75c43926d25c6e5fd2", size = 219256, upload-time = "2026-10-30T15:07:37.686Z" }, + { url = "https://files.pythonhosted.org/packages/59/31/d1636ba67ee9232a60033d90483e48686aa3856014e59110f29015f97bd2/websockets-17.4-cp312-cp312-win_amd64.whl", hash = "sha256:dde9cd67f18803949ebf96de8aba12b8ec5ee3115e34c75a2db85a3b0a6c20d5", size = 219561, upload-time = "2026-10-30T15:07:39.19Z" }, + { url = "https://files.pythonhosted.org/packages/23/aa/e3859d52188f041a5a05c9f3ac005a9c829723f521f0fe60e2c5f9c93bb9/websockets-17.4-cp312-cp312-win_arm64.whl", hash = "sha256:c634053459278cf31fb404ddb5ecd38124e4609e8b609166da621edc2d5796db", size = 219487, upload-time = "2026-10-30T15:07:41.161Z" }, + { url = "https://files.pythonhosted.org/packages/cd/58/eaf27fce59e3f5b9997cd7c77749ef214e077daeffac95479be6ff9f5cfa/websockets-17.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f24bed98595b9d854da8d6debaf82754abf3e8fe63ec90505ef560566814df7e", size = 218769, upload-time = "2026-10-30T15:07:42.558Z" }, + { url = "https://files.pythonhosted.org/packages/13/8e/287eca6d399a953253492189153976676994dfba1b7e82f0f992d14c1404/websockets-17.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:156221ad7638b5abccefd6f798916bf3f8ffd6ac51480eb4ba5b05df914ccbf3", size = 216454, upload-time = "2026-10-30T15:07:43.874Z" }, + { url = "https://files.pythonhosted.org/packages/b3/65/098fd4d221d691395492fcba88c895dde19a51d371b06b8d0be71d3f781b/websockets-17.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:74e46409666c358b93fce0d8c6f4cb107d8dd7cba1302a38d49adf6fa8193c7e", size = 216715, upload-time = "2026-10-30T15:07:45.409Z" }, + { url = "https://files.pythonhosted.org/packages/e9/29/9f9833bc83c1bf2e5597d1ef374d3ccd6467b9b45400cff399c85331ef6c/websockets-17.4-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e3e80cad85ba68c07c1e8d4ccc9cf51e63bf6a73d6bf631640be947bd72b6b63", size = 226096, upload-time = "2026-10-30T15:07:46.929Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/6a95f93661bba2f1a4ec82eb26c6d30e6ba253569ecabb7a675139db6051/websockets-17.4-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:25eb661d8ba7e2b85ebb4e7a1bb9f6a3280910ed10b84330a7abfb5ed32d2764", size = 226382, upload-time = "2026-10-30T15:07:48.332Z" }, + { url = "https://files.pythonhosted.org/packages/80/b0/b0d9427dde0609e2727a9a966fb5fc5c6ef6aa7eba4cfc98791f8b7f1b75/websockets-17.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c74954409ea5789f7a60daa5f94580c00ad0b60b20751c47b35c4784877b5057", size = 227617, upload-time = "2026-10-30T15:07:49.799Z" }, + { url = "https://files.pythonhosted.org/packages/3b/00/fb1016d850d61676d1732434e2361d116c1de369078e59d21f4713115a19/websockets-17.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:47beedf07a706140b50786457e082497ee6b5970c41e49bcd1572ee3f4c73f80", size = 229054, upload-time = "2026-10-30T15:07:51.258Z" }, + { url = "https://files.pythonhosted.org/packages/77/c4/bb666e196541e42237fdb625303ad099005cc835c4e2e0a5d97bb9c4185c/websockets-17.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e282f35ece8895b9fa5af406fc6a4cb42f01e1009525cf46641de584781c83b", size = 228243, upload-time = "2026-10-30T15:07:52.975Z" }, + { url = "https://files.pythonhosted.org/packages/6d/f1/32ae0f45d8464e1606ef3f6a54318d8754b27889de18bb1b2176a19bea39/websockets-17.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:361f9a21a33191d5287e7a75f508fc3b9bf47aaffb0241198d6b7be3384f294e", size = 226995, upload-time = "2026-10-30T15:07:54.574Z" }, + { url = "https://files.pythonhosted.org/packages/f8/9f/5680151ef10e0bfb6f3bf09a992ce6c3e93bbb84fc8ec5d03ad570ac6532/websockets-17.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4073ab7cefe5a2e7dc368c1f01eb27716dc8ea8f1c69e9b7725ebce05aa53cf7", size = 224244, upload-time = "2026-10-30T15:07:56.158Z" }, + { url = "https://files.pythonhosted.org/packages/e2/66/409117b6882b91960598d62b95fac33d70a7aa2e1e1e854c6b64e76712f6/websockets-17.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a50bd9b44dd9b7b845802030b4d88610c01c7f95571b4cbd3a1aeec17a34c9fd", size = 227058, upload-time = "2026-10-30T15:07:57.539Z" }, + { url = "https://files.pythonhosted.org/packages/35/e6/34cab5913bea9d011ae2592a7672340179ff14fb98e889e5e41b071d8134/websockets-17.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:ad2e9e152bec6c4f7e4cdb4adcea6b708400090eec04bfe5ee5b30d368ffd721", size = 225654, upload-time = "2026-10-30T15:07:59.044Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b0/6cfe18e12f23618a3d69723c828037c1282fee7ffce006ae7b5cc0e58ca4/websockets-17.4-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:5830f94a7190a33e55d06d89242ea951ee2009c3a27fc31538f3ac9386b27edd", size = 226425, upload-time = "2026-10-30T15:08:00.492Z" }, + { url = "https://files.pythonhosted.org/packages/c9/71/14d31ea34bafc07c6d96b362a44b301b9a0f2fb260490a8a6cb7db682bc4/websockets-17.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c0cc2cb47face4dae64bd70a9268dbebddb3e48c1b48cf6d7b6ac1471609fd88", size = 227532, upload-time = "2026-10-30T15:08:01.932Z" }, + { url = "https://files.pythonhosted.org/packages/28/69/df3398ca1320a8b76e57ee41053d5c09955383cf60888ffa5771f51a4cc8/websockets-17.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:d0b6a9bd86f865ebc9d847a1eb0a655a0e2b447cbcde743dda97c4298415cc0b", size = 225090, upload-time = "2026-10-30T15:08:03.328Z" }, + { url = "https://files.pythonhosted.org/packages/d6/94/06afe778cf9893e9ac10209c0d4c70aaf0b72289245a8b7efb92cc80927c/websockets-17.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:7a7e9321822ca59ba56fa8744c3e3f01ef74d547aafe0d383d000d7a4d11eb79", size = 226041, upload-time = "2026-10-30T15:08:04.714Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7a/28e9822dbf0bc63341dc45d8d5f1f1f7f375991fc8895bc731105fbde371/websockets-17.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:de29795f23833cdfb68ba45c8a5cc0ec49778ea5deb670188f4465bba5930d25", size = 226323, upload-time = "2026-10-30T15:08:06.103Z" }, + { url = "https://files.pythonhosted.org/packages/5a/d8/606c9c404e82731e4520f6397c8c16549e9cbd39ac583e7ea7d8972a6ae7/websockets-17.4-cp313-cp313-win32.whl", hash = "sha256:37ed7782972545e67d97ef9a172e9499d25459b1e32cb99d1c2a30c572f2441b", size = 219248, upload-time = "2026-10-30T15:08:07.617Z" }, + { url = "https://files.pythonhosted.org/packages/60/a1/17e507dadbfccb755758ba977b165fec92924dfc4a8d2573b4fc1561b0cd/websockets-17.4-cp313-cp313-win_amd64.whl", hash = "sha256:203e42eb77e06f85778a908b34c5ad032f34e98a68ef33920d6685c1e65a9420", size = 219560, upload-time = "2026-10-30T15:08:09.108Z" }, + { url = "https://files.pythonhosted.org/packages/01/ba/4f51fe8db73889ea3ecfdeee283d4ac3b7ad7a609c0e4c1fc6de04078021/websockets-17.4-cp313-cp313-win_arm64.whl", hash = "sha256:d8255971f6789cf0cb365e3e22b9b166eba978548a26241eaa5b7af0440d885a", size = 219496, upload-time = "2026-10-30T15:08:10.574Z" }, + { url = "https://files.pythonhosted.org/packages/1f/5b/085530961668661300de7248f9bf3ba84e98f47875f0fcc87637d024f82b/websockets-17.4-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:d0f943b53bb1d7389d72a5380078670e5fcc34a1328142148b72d20fd82031c7", size = 218810, upload-time = "2026-10-30T15:08:12.14Z" }, + { url = "https://files.pythonhosted.org/packages/f2/fb/5a29e9569f74988822b7bc076287dd7f9f5b68a2070cf5eb4cfada5863d8/websockets-17.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:2fd562372d4afaf18d1c7f1c68e39bd32818bb16d5f57f778a4a4ed88eedcaae", size = 216506, upload-time = "2026-10-30T15:08:13.561Z" }, + { url = "https://files.pythonhosted.org/packages/df/73/eb8544367c13cd87df39d41b74853741fb7182e2a4bb659ad7d36f9066c8/websockets-17.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a0457561e8a87a6a3b509e21c35084d7d207ced262139de3f738e9676a476bbd", size = 216719, upload-time = "2026-10-30T15:08:15.08Z" }, + { url = "https://files.pythonhosted.org/packages/24/fe/c3707e426d9bd779dfad9f319b2b431e5e60d563d7547d3780cbd1646028/websockets-17.4-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7b4ee34acefa9ba1333f02b817982f1e4127f6f9b975017a707c4e738d7f9fb9", size = 226098, upload-time = "2026-10-30T15:08:16.581Z" }, + { url = "https://files.pythonhosted.org/packages/c1/24/d203439f909ffbf37260ca28a3432381412d2e79912ebf98be572e63055e/websockets-17.4-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:ef03fb4b3685df0ed9dc6a074a090f030345cad2c23c61818da3e08e693a9caa", size = 226449, upload-time = "2026-10-30T15:08:18.29Z" }, + { url = "https://files.pythonhosted.org/packages/4b/17/3ae5d9486a170a222dd0437b4f2bc02ecf324177498a942dcac200e65d05/websockets-17.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5e970d3996c597186c9dbb6e77a8048737a834ac03cb13186a54999e0e1c31e", size = 227695, upload-time = "2026-10-30T15:08:19.692Z" }, + { url = "https://files.pythonhosted.org/packages/34/37/1307a8e30a961726f2350982fc01b0b3498db29b030c78c566e65ba64487/websockets-17.4-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6afc32a7a1a40b071070419537df3559d26907086556769683fa97b7b6e90fd5", size = 229069, upload-time = "2026-10-30T15:08:21.682Z" }, + { url = "https://files.pythonhosted.org/packages/9c/bd/4c6167744e202d20a3c770bcde8fae5d427317b1885712c2e02718cd8133/websockets-17.4-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5da7f7f1ecf866186f195f7ecc374c915e1838496b86f2f3b41da27c798a25c3", size = 228296, upload-time = "2026-10-30T15:08:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/14/b3/3438eee41b39afb44c3c6e45dd686b88a7f8d742b96877b77de4fe0e0255/websockets-17.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:043945a43873c7c11a3f75238d475c95f902e967de329eb8763704546cfaa6b6", size = 227045, upload-time = "2026-10-30T15:08:24.749Z" }, + { url = "https://files.pythonhosted.org/packages/46/39/0bac9052d402efaad1b202ff2f1a57b6334aa624d20f509312765601b507/websockets-17.4-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:927d602fb8fb595a69e6b1ae998a6ec19851d0fb9391759456e6425090996647", size = 224297, upload-time = "2026-10-30T15:08:26.275Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7f/5809f6ba5a7d1065301800daf605bdb661a9db5ef868ed189dbf691122ac/websockets-17.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:769e4f7b090e10cae4c082e3e39b9458ec2444505df84953c16c0468b16539c4", size = 227169, upload-time = "2026-10-30T15:08:27.703Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f7/c8f6771e7cc2a038cf78bb12d04d29dbbbabf2a84d76999bcc94532f3020/websockets-17.4-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:03ddf4eb76ced8725dcbb000ff60b0fb8d7330ed011f6dc725a1925c5fe02051", size = 225632, upload-time = "2026-10-30T15:08:29.441Z" }, + { url = "https://files.pythonhosted.org/packages/2c/2f/9104786d952978ca2d011321109e35c05be24c3937ef2a62b4d6e25f7515/websockets-17.4-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:94622cf24e80d03054ceb69a06a86c950e12fe993ed06b933f7895232cacbc3e", size = 226415, upload-time = "2026-10-30T15:08:30.962Z" }, + { url = "https://files.pythonhosted.org/packages/ae/a7/2e1606b3d616b86bb6c70a62d5f87fc9a3dbd81f0bbe24c4706ace76751d/websockets-17.4-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:bc581579885728bb54ef15000295c20e6a64a200b1b73d5cfca71879a3eb3e1f", size = 227594, upload-time = "2026-10-30T15:08:32.443Z" }, + { url = "https://files.pythonhosted.org/packages/67/2d/78ca44e2be6d397aee63a4e68d3a99a33bb14bb3405e94688bc5a2160db5/websockets-17.4-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:f42671900e0b602d05a074c52fd3d757c2f8e5c4f73f771794dae1aa4aea5f0e", size = 225146, upload-time = "2026-10-30T15:08:33.888Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/6dad684e54fc8e09d70c9a095506db5c836207d8e846e3cb1e79424e3492/websockets-17.4-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:2b23dacf7a8a88afe92f77bcdbf4cf043a84692bac2f2da02f4011c687e19b48", size = 226095, upload-time = "2026-10-30T15:08:35.285Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e5/7b04bad7c11c1f92238429352defbac1406743338049afe1328c7a7f95c0/websockets-17.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d48795c7d64ca1c42e3d61fcc6478cb15a19b6ad3f9c882bc8d8dee49d4a420f", size = 226395, upload-time = "2026-10-30T15:08:36.8Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/4eb29c4b12f77b3139470063308ae1e6a0860b9073b1d27d56e8ce19c512/websockets-17.4-cp314-cp314-win32.whl", hash = "sha256:8588edf317fbe4f16a949bc5a6ccdd22b6e6fd5b4745d128bc40bccf31024ce5", size = 218784, upload-time = "2026-10-30T15:08:38.263Z" }, + { url = "https://files.pythonhosted.org/packages/6d/85/2496a24de80c215b55a15f037bc368a2ed0ce7ecb1e909039ff4e76395de/websockets-17.4-cp314-cp314-win_amd64.whl", hash = "sha256:70293c25d79d1f084fdd665894481547575e429d2a75e8d72caec2f6b6b07af8", size = 219137, upload-time = "2026-10-30T15:08:40.112Z" }, + { url = "https://files.pythonhosted.org/packages/9a/a3/cfe95d4eb569035e5a1d2e5cbeb4ccf0eb15a19e1ef2ad819a85960bf375/websockets-17.4-cp314-cp314-win_arm64.whl", hash = "sha256:adc30e5d064c9e33049e825408fa4e952f4e8a0cf4c329dc2ded72e1bb5bae08", size = 219017, upload-time = "2026-10-30T15:08:41.778Z" }, + { url = "https://files.pythonhosted.org/packages/2b/dd/4143048a2b27303e7de8ef53d7d0ee3987734fbf93e09491d5a1b0a55187/websockets-17.4-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:bbb6bed49f083e2ec8ae0bb21c00c7c5171ab8e08a8b008c61a43fc6c944fdac", size = 219141, upload-time = "2026-10-30T15:08:43.184Z" }, + { url = "https://files.pythonhosted.org/packages/a8/3e/a63b5f3a5c24be2898eb22a3093a56d4ac4cd24ae79e7ab7a1b971ed4611/websockets-17.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:c7a56140fcbf4662cb263754a754c651a16fe2196cae1fd232d18f89acd30c83", size = 216675, upload-time = "2026-10-30T15:08:44.682Z" }, + { url = "https://files.pythonhosted.org/packages/d6/80/f238a10f0b23853c665c602a42784023995ac26674e480252c21af39f4f8/websockets-17.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:18d3710becc612ec6f0229425bd6495133dfcbf30f7b6569585acc8ed2f1b452", size = 216880, upload-time = "2026-10-30T15:08:46.304Z" }, + { url = "https://files.pythonhosted.org/packages/d1/b1/899b69aba1e8d65ac5bfe90b97ada22a815f1dcd3840bf188104738aac33/websockets-17.4-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:00ad98e4bb0df7a6711c645eec16d5a9fdf99f0692bd4f5b6cb85a68677ba8df", size = 226462, upload-time = "2026-10-30T15:08:47.723Z" }, + { url = "https://files.pythonhosted.org/packages/28/a8/598c2b2a22dfe14d352400df804db8b78a68c1498b3f775a658f07f21618/websockets-17.4-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:7849a096d6fdba3f2bdf849eb89f2d233a24400c92faa3efb25fa8dc615b706c", size = 226741, upload-time = "2026-10-30T15:08:49.314Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ad/84a6de3cc3dd4ee336428c31f89a82e002299f83e10d967f0e9a5cbaf591/websockets-17.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e30550965c78223439815dbdf40c93eb8931dfbf12427110dcfcaeebef76feb6", size = 227914, upload-time = "2026-10-30T15:08:50.746Z" }, + { url = "https://files.pythonhosted.org/packages/69/ab/1e191b97d60a934c071b7b73c39c5db39721a925cc53acd929c615f85550/websockets-17.4-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:725be1aff55f1c873a79cea0f612df9dff21a9d2c2e05783665b824b8aa7c24e", size = 230059, upload-time = "2026-10-30T15:08:52.596Z" }, + { url = "https://files.pythonhosted.org/packages/f2/57/ef8a64732ef4367091ab05f9b22c1ee4c28657d4a0d088a644198eb5ded6/websockets-17.4-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:b6c7f91520c29420639925fd1cecceac9ca07366b50c09ea24eac1cd116b4866", size = 228486, upload-time = "2026-10-30T15:08:53.967Z" }, + { url = "https://files.pythonhosted.org/packages/48/1f/dbad3afcacf2c52d1fdf83b611d849598f0a047d7333ff476266532877b8/websockets-17.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:6531540aa63e6864cb0615a3a5da70ae03191334507852a5385320bb7916df3f", size = 227216, upload-time = "2026-10-30T15:08:55.687Z" }, + { url = "https://files.pythonhosted.org/packages/5b/47/59e325d6ca3e04ba5cc7a139d891ef83cad3fb460a183c8f359f378b69a9/websockets-17.4-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0a57b99f2e28922b5a2434317580fd23fdf118caff4c5b752f5452836426205a", size = 224755, upload-time = "2026-10-30T15:08:57.203Z" }, + { url = "https://files.pythonhosted.org/packages/b8/b6/28a471318dfb0060b58c47d0a252cb5078528a1aa1fdf5e6e88e2a61cf18/websockets-17.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8fd30d217a4275107667fe1d4f601e2d50c797d0727148cfbb384536d65f04d3", size = 227508, upload-time = "2026-10-30T15:08:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/ee/29/7485ac6fc4b342b43964811381f56276fec967cae6a851ae4b815613b10c/websockets-17.4-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cc0cd4065a65ac98f3e2742ee9f314da9d224db49b07dc17d3a20cef0d79658d", size = 225961, upload-time = "2026-10-30T15:09:00.414Z" }, + { url = "https://files.pythonhosted.org/packages/95/a6/520e1f7aa9644ddf58f5a51fc37f46e15293a68cd35b70d5b81b7331ca1e/websockets-17.4-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:71f76bb8e59be847330b8a8d3753f85397677e128f9f9692c215f8cf721cefc7", size = 226851, upload-time = "2026-10-30T15:09:01.979Z" }, + { url = "https://files.pythonhosted.org/packages/e5/0d/444799abe7418f361da8c201c6858b64b4e8d47265f90851e5cb68b4d90f/websockets-17.4-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:c2db7b9e2d726f7e051bedb67abcf460b84b11437b2f9fdacda7e6931dace85b", size = 227869, upload-time = "2026-10-30T15:09:03.405Z" }, + { url = "https://files.pythonhosted.org/packages/cb/86/6da20322a07364a0ab0787a2b0d4367770f59404fdab6e35122413a7f63e/websockets-17.4-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:332b88022d0acd47c44158bcd43f47f14eaddcd979247f242b1a33291c45cdd1", size = 225562, upload-time = "2026-10-30T15:09:04.891Z" }, + { url = "https://files.pythonhosted.org/packages/2a/da/53e44d96238dc207011ad5d93b0540c58e1c680a86f48dc3fa8e5138b343/websockets-17.4-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5cec3e7fbc911ff4fcf43b24aaf1b96906381ad36030f42897def3ff4b78729e", size = 226334, upload-time = "2026-10-30T15:09:06.42Z" }, + { url = "https://files.pythonhosted.org/packages/18/08/82cea972a87f229ee1903e9adf74c17d1e6c4371d581ebb11ccbed4e3a7b/websockets-17.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:cbdf4b42f4514422051889424fd03bc269be8c5d751bf39ec29ad761590bd10d", size = 226767, upload-time = "2026-10-30T15:09:07.837Z" }, + { url = "https://files.pythonhosted.org/packages/96/f3/ee6afff802e39e8d6ef29ee4bdc30f8272aaa38295c19a911fad91fe95fc/websockets-17.4-cp314-cp314t-win32.whl", hash = "sha256:16550e24ac22c27e0a728100d8de196b5f054bab6748ef9f0b168fb8b3c32e35", size = 218918, upload-time = "2026-10-30T15:09:09.31Z" }, + { url = "https://files.pythonhosted.org/packages/11/56/b0b07917f9c85a4d24a37300f4ae888bfa7c20f08902dd6a5c61a0d1b26f/websockets-17.4-cp314-cp314t-win_amd64.whl", hash = "sha256:5ec906bb21b35e66cfdcc2ea0133f249f52b7d89e3e45ec8d2bd2d84a0255d7d", size = 219260, upload-time = "2026-10-30T15:09:10.832Z" }, + { url = "https://files.pythonhosted.org/packages/19/a6/a63113909ea602d3d22b0f32a7a9950d8d18b725cfdce735eab9b5f5d198/websockets-17.4-cp314-cp314t-win_arm64.whl", hash = "sha256:c00f0c45851a2c61efffd03dde8fb4d594026b5cc18196c94e15460f1225f2ed", size = 219176, upload-time = "2026-10-30T15:09:12.444Z" }, + { url = "https://files.pythonhosted.org/packages/ee/be/4032fde05e62d1c52edd250fda475e910cac0cd180e377690bff24147b5e/websockets-17.4-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:8c51ac7b31578a7275650f580aac985940985b6d2e57247ac6d5e07f2c936cd6", size = 218740, upload-time = "2026-10-30T15:09:13.833Z" }, + { url = "https://files.pythonhosted.org/packages/74/1c/b47f5786eb45599072411571651606fb22f6e825d522d627daad974ea636/websockets-17.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:023dc13bdc42a55e152acc81c39c90ec6cc4159ed17d23c6d73460fa2a73ab16", size = 216470, upload-time = "2026-10-30T15:09:15.394Z" }, + { url = "https://files.pythonhosted.org/packages/70/98/0021f55de633617b4a8390cca17e700c9ba5d99323103128412dc2c15aca/websockets-17.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6fd8cac4907fec8302726d49e6969acfffaf720bc39b1cee23f473b81f4dce01", size = 216695, upload-time = "2026-10-30T15:09:17.185Z" }, + { url = "https://files.pythonhosted.org/packages/28/56/2c67389b47c4b9e9e9318d9b3e4bb52a2fef3749ff00b0b151a342c4d42d/websockets-17.4-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:4441d655a53185ef1b01b1d42ad9b3a96b905110a9219043e3fdaec855ba3b6e", size = 226134, upload-time = "2026-10-30T15:09:19.156Z" }, + { url = "https://files.pythonhosted.org/packages/75/bd/ee3a679a10741a0cdd7aa8bdd6d03999069672826aa7a6495fdf589ed961/websockets-17.4-cp315-cp315-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3acc45494c08a4d27375a2c28474537f68910219f42624a08011221b04623d04", size = 226569, upload-time = "2026-10-30T15:09:20.587Z" }, + { url = "https://files.pythonhosted.org/packages/c4/42/b293a5d07099549797138d09fda5bf878d302b4980e61678981c8dfdc98f/websockets-17.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3b78b39377630a70aa2198e5f03be416e690364a046b1d8af80a9263733083d0", size = 227726, upload-time = "2026-10-30T15:09:22.015Z" }, + { url = "https://files.pythonhosted.org/packages/2d/81/d048ff83c4d0fc386f6008529d12690d0dcb410f73570430f13fe4d543f0/websockets-17.4-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6cf4c002268da5c11cae9083aec71ac943bce9d95e0f83c8bf9a95a3ce421fbb", size = 229426, upload-time = "2026-10-30T15:09:23.444Z" }, + { url = "https://files.pythonhosted.org/packages/e6/21/1df51f94047dfb76c32fd7508036e4b55352d0f04fd0e3bee525a2122225/websockets-17.4-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ed7fe197b8bb66eef4f62c052e33752d456d2fdda74805469d4bd954950ab339", size = 228211, upload-time = "2026-10-30T15:09:24.902Z" }, + { url = "https://files.pythonhosted.org/packages/cf/13/33d6a28471da4c30a98a2313c76f984be2056a703c5c532225dc28f5dba3/websockets-17.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f0494d3d97502e270282cc6a1f8648cd7335b4fe8d5c452006e5b7f9d62b8892", size = 227106, upload-time = "2026-10-30T15:09:26.315Z" }, + { url = "https://files.pythonhosted.org/packages/4a/86/ff8441e56ca677e51f9c826868fccde2a82bafe0ffa337fd38823b64253a/websockets-17.4-cp315-cp315-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ab9e4bd60796866c578e3afa0a17c98636887827a39c2e238a61989c18fd8e7b", size = 224499, upload-time = "2026-10-30T15:09:28.116Z" }, + { url = "https://files.pythonhosted.org/packages/da/91/470d7a619ce4aa837ff5b6a5836227c43bdfdc42ef837cce48f508992438/websockets-17.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8d148b4b295224d3a19e7bd9f02ebe7344de254b3b2c4d0628ce42ade0bca119", size = 227213, upload-time = "2026-10-30T15:09:29.847Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ba/55ed1422d6c73b5b81996ca195f2a256a339b26c553f5686afc2a926bc2b/websockets-17.4-cp315-cp315-musllinux_1_2_armv7l.whl", hash = "sha256:6597a1f7413189b4bc58437babcdf39b79da416e5c477ae98323a88ecc108188", size = 225876, upload-time = "2026-10-30T15:09:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/e9/59/f133d260e7a48d3e231c3a495eeb6114b880c1e96bfc781a949c1f73991c/websockets-17.4-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:a9b0026538719f7a532998d84640ab2e91ca1a051ce4b8d924fdcb607307e921", size = 226403, upload-time = "2026-10-30T15:09:33.199Z" }, + { url = "https://files.pythonhosted.org/packages/45/16/bb3355453ffdc31d3a14ddc0b50e058f13a97d2ed019ba6c380e03456169/websockets-17.4-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:a703f23ca15a51251fc94f1774683f5aa511588a7ad6bbb83960cdb2a4dcd978", size = 227558, upload-time = "2026-10-30T15:09:34.703Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/f3d55a83c2a4daa8bf62594b00a721dc8767518ccb833f932b0178eb6c19/websockets-17.4-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:6b061ea7ca94966af7cd7a87cb189ff15972c103244611a2b1e8408c04f1dbe6", size = 225369, upload-time = "2026-10-30T15:09:36.204Z" }, + { url = "https://files.pythonhosted.org/packages/88/66/3a320bfb718d9ae1eff15ba7790979c0e6fdec74e388430f426e6647d7f4/websockets-17.4-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:e6d2a185ec4ff0478089305abd833da3a9fda8803eb77325b89ebeae5585a3b7", size = 226268, upload-time = "2026-10-30T15:09:37.565Z" }, + { url = "https://files.pythonhosted.org/packages/da/ee/1f9cdeeaaa2d5e158b7a40f971e74b641b35f977674b46229a5bb14e270a/websockets-17.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:9a4e95d56994a45ac76541853796720436ffe462957d0b1b89e87ff3d3b1627e", size = 226530, upload-time = "2026-10-30T15:09:39.171Z" }, + { url = "https://files.pythonhosted.org/packages/da/28/506406ef09e6e168796f0187bdac0767f38a560e6785c4ee26e583aaaf76/websockets-17.4-cp315-cp315-win32.whl", hash = "sha256:b7ea61af293a153f2d67430038cf0efc10140caa623f2bdf5a9f5a457ff20f57", size = 218751, upload-time = "2026-10-30T15:09:40.748Z" }, + { url = "https://files.pythonhosted.org/packages/25/a6/818647a9a9b3ee8bf131e9ab4fa1f2db9c6539f08e7084dd57549e0bd49d/websockets-17.4-cp315-cp315-win_amd64.whl", hash = "sha256:8b45d40f07081b377f0b837ddbfba4a9ab4a89a7b569d3c095436564e767a27b", size = 219045, upload-time = "2026-10-30T15:09:42.251Z" }, + { url = "https://files.pythonhosted.org/packages/3d/b2/0338a9abec3df8556627af987352657ce1c8456f2060b54741570b174122/websockets-17.4-cp315-cp315-win_arm64.whl", hash = "sha256:29b615c2d5dd883f89c107a782681b73a7aa8b2bd894130310e45eb09b143913", size = 218957, upload-time = "2026-10-30T15:09:43.866Z" }, + { url = "https://files.pythonhosted.org/packages/68/92/22e83d003cdbd22be5d35e28c260203e9fbb6c73b17a8e1509f4ad49e74d/websockets-17.4-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:c568e72f5425a74616daeb824afe28da460cbeea036432f41c6af5380b83300d", size = 219056, upload-time = "2026-10-30T15:09:45.528Z" }, + { url = "https://files.pythonhosted.org/packages/2f/ca/071d38e7237f6ada4f577b74f7cbf5bc2ff7e1f9360ebd2837e74a22dfd4/websockets-17.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:bfc86dff091104eec770c29ea1831dbe191968a70aa2d8ae8eda3240d863970a", size = 216630, upload-time = "2026-10-30T15:09:46.951Z" }, + { url = "https://files.pythonhosted.org/packages/fa/76/22d4523f92d88b8f5ebfd3df7ab5e825146af100f7e2caeae7d359ae51ea/websockets-17.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:f5f06f59e19aa0770aaf651ce91c196fa620b35aed49a7e6c36e7335f3f83db7", size = 216841, upload-time = "2026-10-30T15:09:48.285Z" }, + { url = "https://files.pythonhosted.org/packages/87/29/bc94be4a8bc19ef518e9efecd90a992f2991b7cfc6eb8a7430c4e2dc097c/websockets-17.4-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:8f32a6cb0b101170abc2d8053af1473a2a29ef2a06d7130994ee8455a50f5dbf", size = 226992, upload-time = "2026-10-30T15:09:49.776Z" }, + { url = "https://files.pythonhosted.org/packages/fa/25/58f69b5fec064764ddf5b88045397433cdb028f5b17c82fbe047fd31fff7/websockets-17.4-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:72d0a731eccf482d5661c6711abfcd5921f3dbfbbb0789061e1918ef4bc89c70", size = 227258, upload-time = "2026-10-30T15:09:51.172Z" }, + { url = "https://files.pythonhosted.org/packages/21/7c/bc932a54c5f1bd78461574aea539fc562fd2de494738a2c0675c4de860be/websockets-17.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:48c83103f82fce36191a9e3a8a80731d4340e2da544eae8c5aaaf6a45280e7d0", size = 228589, upload-time = "2026-10-30T15:09:52.628Z" }, + { url = "https://files.pythonhosted.org/packages/c4/92/57ec83066d0bfa8a9b9f594bc61951073c4a86e34c562a5292604118dab6/websockets-17.4-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c8052c3058c402d53602583da5ddcf1a15a63ab1efe0222f47c7be59944e6463", size = 230217, upload-time = "2026-10-30T15:09:54.058Z" }, + { url = "https://files.pythonhosted.org/packages/6e/fc/0f2fe533b5b4dc22ac704b3357f5c99fa60a3837218b3c6c6ad63a60120e/websockets-17.4-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:0c22a9c6b2349204f56123dd0ca7779e989d68e336d0dc02ad823485d44925de", size = 229026, upload-time = "2026-10-30T15:09:55.727Z" }, + { url = "https://files.pythonhosted.org/packages/7c/cc/ed28307835106a9a2dbd1a5efc597e8befa3d0a5f2b46a4c1e466b2f4759/websockets-17.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0dcce83837328e6795225ead920d3aa8d867cc9d6922aa558b0e9111599fdbb9", size = 227904, upload-time = "2026-10-30T15:09:57.221Z" }, + { url = "https://files.pythonhosted.org/packages/39/4d/24ad7deddc7b31c3e430acc1c00c7b384ae42f1f973e9cc01aa42d19628f/websockets-17.4-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4b79ea31cf277c72d2307c6cb8bd32a2c151959e80a2f24fa85df620c5f2860c", size = 225253, upload-time = "2026-10-30T15:09:58.624Z" }, + { url = "https://files.pythonhosted.org/packages/93/f6/9c92230ebfab42fee482b236c45c32ed34b24f7360080b400cce6cfcac11/websockets-17.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:3d27153a0413696767b98b5d96173a2a7e27cbfca02000a6069cea7b977765a7", size = 228089, upload-time = "2026-10-30T15:10:00.308Z" }, + { url = "https://files.pythonhosted.org/packages/fe/7a/f523830e562da9b1d7a610174752753720c5e47e84b59b5fc47721d416bd/websockets-17.4-cp315-cp315t-musllinux_1_2_armv7l.whl", hash = "sha256:e0feb03a338f8f5e819ae23a73aabb7b46fd3b73f15f7df782dd12d99e2b02ad", size = 226743, upload-time = "2026-10-30T15:10:01.744Z" }, + { url = "https://files.pythonhosted.org/packages/2c/e6/d1a56495cb7b1a0a4688145131be38cfd0c1342bde8125e136a6e6ee494e/websockets-17.4-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9ff89e36451a19775e7556d95ebfa4a0b24b84cc87565d6b5d0ec8ea82bf3f2c", size = 227237, upload-time = "2026-10-30T15:10:03.417Z" }, + { url = "https://files.pythonhosted.org/packages/44/41/c4e53f7ad63838d7eba6e82c5d743827e91dafe5e48c88a58f7e90043945/websockets-17.4-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:ee6c4e0085bff5f6621bf9c53452584dcb91ebd993ce841e1f4061ac12b6b556", size = 228348, upload-time = "2026-10-30T15:10:05.149Z" }, + { url = "https://files.pythonhosted.org/packages/ca/01/f6f78c3edeb8ad2b3c35a8c4117ec2cf9346215afaed8155af1e7933818b/websockets-17.4-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:1962f3bfde085af18878f1bb1aafb300c9a6ac33da886d0b0d97e33c9ce7a222", size = 226099, upload-time = "2026-10-30T15:10:06.588Z" }, + { url = "https://files.pythonhosted.org/packages/8d/01/d8c11740231b63d1aba6bad6b1d4e72e8384b26c5448801da238ebe82c92/websockets-17.4-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:42d7a6e818214336cf7af9a3aae5c6923f94f09fa07ac5aab98268ba2a98a6d5", size = 226956, upload-time = "2026-10-30T15:10:08.141Z" }, + { url = "https://files.pythonhosted.org/packages/99/87/dbfd43ae01ea8fdb7478a1b3d58b32aca83bb9c4aa61ebe187d1e188ac8e/websockets-17.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c9f8fdb7bbefc4907c2bb3593f810f2b67a2d5329e1d38724a1aa3d763cf63eb", size = 227253, upload-time = "2026-10-30T15:10:09.533Z" }, + { url = "https://files.pythonhosted.org/packages/bf/8e/fbd968a75428063560ada02d564de8d6c49ca34ec29dfb78e5d900f4b0ef/websockets-17.4-cp315-cp315t-win32.whl", hash = "sha256:506623128d7a55b726a5a46e4c9a8eae4c9dd0f04ff60b041fe7df85b9d034fe", size = 218877, upload-time = "2026-10-30T15:10:10.925Z" }, + { url = "https://files.pythonhosted.org/packages/f9/53/8f37a3943517bba77fc86f7c4162c455018c5b6d760c5e9c9a11de9e37f7/websockets-17.4-cp315-cp315t-win_amd64.whl", hash = "sha256:6e6558efbb256b532c9f06a21ba42bcac729718e365c505819f181f25e5c0eca", size = 219195, upload-time = "2026-10-30T15:10:12.336Z" }, + { url = "https://files.pythonhosted.org/packages/69/35/cf33cba7248fcd80cfe5911ffe67aa2637f50c2bfaada123b1e9d2aeca90/websockets-17.4-cp315-cp315t-win_arm64.whl", hash = "sha256:fcac44d917672ad6257ad64b80b5168306f168a78cab5c0612e4c699caed18cf", size = 219117, upload-time = "2026-10-30T15:10:13.771Z" }, + { url = "https://files.pythonhosted.org/packages/a0/80/78c580302991d229ac5ad0a00c361916f7f84deaf6dd76370034dd8e7383/websockets-17.4-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:73b00645316121105274fd266ed54a20e6514650126d399cdea39876ab1e7b04", size = 216364, upload-time = "2026-10-30T15:10:15.472Z" }, + { url = "https://files.pythonhosted.org/packages/d9/27/7d18d381994c7c27a855131ae064ff43ec00ded636b7c6ead4abb4cec841/websockets-17.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:02f380df26de14999ecace203fe1396ac14d1c6132afc7924eb6f8c8b646c69d", size = 216642, upload-time = "2026-10-30T15:10:17.153Z" }, + { url = "https://files.pythonhosted.org/packages/fc/91/43e73997fbdc7ef3cb434148888329113a07b66d97a8ea6aa2f93e574028/websockets-17.4-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f5b1d315a615cec81a79e2ce3a94221dc5c23e7fd4012897085d3b5e5a5638d0", size = 217587, upload-time = "2026-10-30T15:10:19.123Z" }, + { url = "https://files.pythonhosted.org/packages/a8/17/5e3e6be945512aff7351c9f60134803902ccb07cd7d6c9becdfa349a32d5/websockets-17.4-pp311-pypy311_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:046ed16d3d83d64594e4a40655fef061ccf36059d8c30a01feca8a9481fe13b8", size = 217478, upload-time = "2026-10-30T15:10:20.665Z" }, + { url = "https://files.pythonhosted.org/packages/7d/5f/0a1ee98aeff04c200492a479a386ff106d1ef6d5c9d6613959b3e3d79469/websockets-17.4-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f772007dfba8941873dbd276b6a6845428cc740888b5c6c37bf483b1ea34b42", size = 218371, upload-time = "2026-10-30T15:10:22.35Z" }, + { url = "https://files.pythonhosted.org/packages/17/97/acb333fa9a54bb1ad616c1add65185f9ab580c3c76366a3d1abc1090979b/websockets-17.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:accb5e9492b9bc9c9aeec5b72ea8f2ddcbefc6143d1c626fba960ecbdc89807e", size = 306811, upload-time = "2026-10-30T15:10:23.76Z" }, + { url = "https://files.pythonhosted.org/packages/e9/a3/d8fbc72c5c0e78905caf2d6dcf806e532451e3f48e2a09a8ebe1de9ad412/websockets-17.4-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:c7f66a53e9b7ec831abb15e3d9b6cee8f52d6a24cd0a374786bf46c3ec218bc6", size = 216397, upload-time = "2026-10-30T15:10:25.255Z" }, + { url = "https://files.pythonhosted.org/packages/d3/de/1bf313cd0f4662df4884a7602932cd13347090e59dd6047865eee2bb5aa5/websockets-17.4-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:4fb2db1f649b6464711846b5bb9c1611bd906ce939d9460cbd1fa419552cd6c3", size = 216664, upload-time = "2026-10-30T15:10:27.016Z" }, + { url = "https://files.pythonhosted.org/packages/30/e2/7912bd417511b54907853bd495aef2daee111062dbafd43d133a3f7253a7/websockets-17.4-pp312-pypy312_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:32110d954d9d0e51f36edb0396673bf4d35193a0a80ba7013bf7f7d58a33ca07", size = 217603, upload-time = "2026-10-30T15:10:28.475Z" }, + { url = "https://files.pythonhosted.org/packages/56/6f/2e8d5610f6184a2e1720bf8ce256402ed99ad30ea87c461fba5bc4d651d9/websockets-17.4-pp312-pypy312_pp80-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:88ba8a439b2bad97bb69c38db5bf0ec16a061ee834cf0f244089186ee803e899", size = 217489, upload-time = "2026-10-30T15:10:29.999Z" }, + { url = "https://files.pythonhosted.org/packages/29/3a/a05bc57eadcd7e8e072d917888128e6d22e1203984afb21a8da3198982fe/websockets-17.4-pp312-pypy312_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:868744c68e9342768888c7326604da2228c19bb6946aa46b5f9e1ac32ea8d40b", size = 218356, upload-time = "2026-10-30T15:10:31.432Z" }, + { url = "https://files.pythonhosted.org/packages/b2/49/eed86bfb8863093a82cbaa52c9159be1ce2374d5ace6fe1f8e8031567e7d/websockets-17.4-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:829bcaa90be8737c132d9515d6a466e8528e3b3d050d3f3466f36ea94d3beb48", size = 306838, upload-time = "2026-10-30T15:10:32.954Z" }, + { url = "https://files.pythonhosted.org/packages/eb/27/9db924cb0dbf22eade78d98fbae77790f9bf6bc729e6ab29aef9d68e4156/websockets-17.4-py3-none-any.whl", hash = "sha256:c6bd2c9781915592b209160d0f017d4c7c82ad53075e6b0c24d2a89299e7f9e9", size = 212900, upload-time = "2026-10-30T15:10:34.482Z" }, ] [[package]]