diff --git a/.github/workflows/fdroid.yaml b/.github/workflows/fdroid.yaml index f986508fb..3829a32b6 100644 --- a/.github/workflows/fdroid.yaml +++ b/.github/workflows/fdroid.yaml @@ -22,6 +22,13 @@ on: - src-tauri/gen/android/** - .github/workflows/fdroid.yaml - .github/workflows/fdroid-build.yaml + - crates/vector-gpui/scripts/fdroid-build.sh + - crates/vector-gpui/android/** + - crates/vector-gpui/Cargo.toml + - crates/vector-gpui/Cargo.lock + +permissions: + contents: read concurrency: group: fdroid-${{ github.ref }} @@ -81,3 +88,47 @@ jobs: path: src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-universal-release-unsigned.apk if-no-files-found: error + # The GPUI client's flavour, from its own recipe: the app v0.6 ships on F-Droid. + gpui: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@stable + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + + - uses: android-actions/setup-android@v4 + + - name: Android NDK + run: | + sdkmanager --install "ndk;29.0.14206865" + echo "NDK_HOME=$ANDROID_HOME/ndk/29.0.14206865" >> "$GITHUB_ENV" + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - name: Prepare (network stage) + run: crates/vector-gpui/scripts/fdroid-build.sh prepare + + - name: Build + run: crates/vector-gpui/scripts/fdroid-build.sh build + + - uses: actions/upload-artifact@v6 + with: + name: Vector-GPUI-fdroid-unsigned + path: crates/vector-gpui/android/app/build/outputs/apk/release/*.apk + if-no-files-found: error diff --git a/.github/workflows/gpui-android.yaml b/.github/workflows/gpui-android.yaml new file mode 100644 index 000000000..18aeebe53 --- /dev/null +++ b/.github/workflows/gpui-android.yaml @@ -0,0 +1,258 @@ +name: GPUI Android + +# The GPUI client for Android phones, compiled with the runner's NDK: its platform +# (crates/vector-gpui/vendor/gpui_android) and the client itself. Its own concurrency group, so +# it never waits behind or replaces a desktop build. +on: + push: + branches: [gpui] + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - 'crates/vector-core/**' + - 'crates/vector-calls/**' + - 'src-tauri/src/**' + - '.github/workflows/gpui-android.yaml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: gpui-android-${{ github.ref }} + cancel-in-progress: true + +env: + RUST_TOOLCHAIN: 1.98.0 + CARGO_TERM_COLOR: always + +jobs: + check: + strategy: + fail-fast: false + matrix: + include: + - name: platform + # Expected to fail until the client's desktop-only dependencies are ported. + - name: client + experimental: true + name: check (${{ matrix.name }}) + continue-on-error: ${{ matrix.experimental || false }} + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: aarch64-linux-android + components: clippy + + - name: NDK toolchain + run: | + ndk="$ANDROID_NDK_LATEST_HOME" + bin="$ndk/toolchains/llvm/prebuilt/linux-x86_64/bin" + { + echo "ANDROID_NDK_HOME=$ndk" + echo "ANDROID_NDK_ROOT=$ndk" + echo "ANDROID_NDK=$ndk" + echo "CC_aarch64_linux_android=$bin/aarch64-linux-android26-clang" + echo "CXX_aarch64_linux_android=$bin/aarch64-linux-android26-clang++" + echo "AR_aarch64_linux_android=$bin/llvm-ar" + echo "CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=$bin/aarch64-linux-android26-clang" + } >> "$GITHUB_ENV" + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-aarch64-${{ matrix.name }} + + # Warnings fail only in our own platform crates: -D warnings would reach the vendored ones too. + - name: Clippy + if: matrix.name == 'platform' + shell: bash + run: | + cargo clippy --locked -p gpui_platform -p gpui_android --target aarch64-linux-android \ + --message-format short 2>&1 | tee clippy.log + ! grep -E '^vendor/gpui_(android|platform)/.*: (warning|error)' clippy.log + + - name: Check + if: matrix.name == 'client' + run: cargo check --locked --keep-going --lib --target aarch64-linux-android --no-default-features --features tor,i2p --message-format short + + # The app around the client: Kotlin, manifest and resources, which need no Rust to compile. + shell: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui/android + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - name: Compile + run: ./gradlew --no-daemon :app:compileDebugKotlin :app:compileReleaseKotlin + + # The phone app: a debug APK for arm64 phones, which installs beside an installed Vector. + apk: + needs: shell + # Expected to fail until the client links for Android. + continue-on-error: true + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: crates/vector-gpui/android + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: aarch64-linux-android + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-apk + + # One debug key across runs, so a test APK installs over the last one without an + # uninstall (which wipes the app's data). The secret holds it for good; the cache is + # evicted once the repo's caches pass 10 GB, and Gradle then makes a new key. + - name: Debug key + id: debug-key + env: + KEYSTORE: ${{ secrets.GPUI_ANDROID_DEBUG_KEYSTORE }} + run: | + if [ -n "$KEYSTORE" ]; then + mkdir -p ~/.android + printf '%s' "$KEYSTORE" | base64 -d > ~/.android/debug.keystore + echo "secret=1" >> "$GITHUB_OUTPUT" + else + echo "::warning::GPUI_ANDROID_DEBUG_KEYSTORE is not set: this APK's key lasts only as long as the Actions cache" + fi + + - if: steps.debug-key.outputs.secret != '1' + uses: actions/cache@v4 + with: + path: ~/.android/debug.keystore + key: gpui-android-debug-keystore-v1 + + - name: Build + run: ./gradlew --no-daemon :app:assembleDebug -PvectorNdk="$(basename "$ANDROID_NDK_LATEST_HOME")" + + - uses: actions/upload-artifact@v4 + with: + name: vector-gpui-android-arm64-debug + path: crates/vector-gpui/android/app/build/outputs/apk/debug/*.apk + retention-days: 14 + + # The app on emulated phones (x86_64, software GPU): what it shows after launch, and its log. + # Android 11 without Vulkan is the GLES path phones with PowerVR GPUs draw with. + emulator: + needs: shell + continue-on-error: true + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - { api: 34, gpu: vulkan, features: '' } + - { api: 30, gpu: gles, features: '-feature -Vulkan' } + name: emulator (API ${{ matrix.api }}, ${{ matrix.gpu }}) + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: x86_64-linux-android + + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + cache: gradle + + # Google's copy of Maven Central ahead of every repository: Central's CDN answers some + # runners 404. An init script, since F-Droid's scanner refuses unknown repositories. + - name: Maven mirror + run: | + mkdir -p ~/.gradle/init.d + cat > ~/.gradle/init.d/mirror.gradle <<'EOF' + beforeSettings { settings -> + def mirror = 'https://maven-central.storage-download.googleapis.com/maven2/' + settings.pluginManagement.repositories.maven { url = mirror } + settings.dependencyResolutionManagement.repositories.maven { url = mirror } + } + EOF + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> target + key: android-emulator + + - name: Build + working-directory: crates/vector-gpui/android + run: ./gradlew --no-daemon :app:assembleDebug -PvectorAbis=x86_64 -PvectorNdk="$(basename "$ANDROID_NDK_LATEST_HOME")" + + - name: KVM + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + + - uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: ${{ matrix.api }} + arch: x86_64 + target: google_apis + emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -noaudio -no-boot-anim ${{ matrix.features }} + disable-animations: true + script: crates/vector-gpui/android/scripts/emulator-smoke.sh crates/vector-gpui/android/app/build/outputs/apk/debug/app-debug.apk smoke + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: vector-gpui-android-emulator-${{ matrix.api }} + path: smoke/ + retention-days: 14 diff --git a/.github/workflows/gpui.yaml b/.github/workflows/gpui.yaml new file mode 100644 index 000000000..7a37baca8 --- /dev/null +++ b/.github/workflows/gpui.yaml @@ -0,0 +1,470 @@ +name: GPUI build + +# The GPUI client on the platforms the cloud box can't build for. Its own workspace and lockfile, +# so nothing here touches the Tauri client's build. +on: + push: + branches: [gpui] + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - 'crates/vector-core/**' + - 'crates/vector-calls/**' + - 'src-tauri/src/**' + - '.github/workflows/gpui.yaml' + pull_request: + paths: + - 'crates/vector-gpui/**' + - 'crates/vector-i18n/**' + - '.github/workflows/gpui.yaml' + workflow_dispatch: + # A release (publish.yaml) builds the updater bundles here, then signs and uploads them itself. + workflow_call: + inputs: + release_tag: + type: string + required: true + +permissions: + contents: read + +# A build takes most of an hour; a newer push waits for it rather than cancelling it. +concurrency: + group: gpui-${{ github.ref }} + cancel-in-progress: false + +env: + RUST_TOOLCHAIN: 1.98.0 + CARGO_TERM_COLOR: always + +jobs: + build: + # The port's own pull request builds on its pushes already. + if: ${{ !inputs.release_tag && (github.event_name != 'pull_request' || github.head_ref != 'gpui') }} + strategy: + fail-fast: false + matrix: + include: + # The arm64 pool rarely takes a job; the release builds use this one too. + - platform: macos-26-intel + features: '' + # No system FFmpeg on the runner: video attachments draw as files here for now. + - platform: windows-2022 + features: '--no-default-features --features tor,i2p' + runs-on: ${{ matrix.platform }} + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + + - name: Prepare the runner (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + Set-MpPreference -DisableRealtimeMonitoring $true + $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE + echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV + + - name: FFmpeg (macOS) + if: startsWith(matrix.platform, 'macos') + run: | + brew install ffmpeg@7 pkg-config + echo "PKG_CONFIG_PATH=$(brew --prefix ffmpeg@7)/lib/pkgconfig" >> "$GITHUB_ENV" + + # Whisper transcribes on Vulkan on x64 Windows, as the desktop client does. + - name: Cache Vulkan (Windows) + if: startsWith(matrix.platform, 'windows') + id: vulkan-cache + uses: actions/cache@v5 + with: + path: C:\vcpkg\installed + key: vulkan-x64-windows-headers-loader-spirv-tools-glslc + + - name: Install Vulkan SDK (Windows) + if: startsWith(matrix.platform, 'windows') && steps.vulkan-cache.outputs.cache-hit != 'true' + shell: pwsh + working-directory: . + run: | + vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows + Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + New-Item -ItemType Directory -Force -Path $vcpkgBin + Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force + + - name: Vulkan environment (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "$vcpkgBin" >> $env:GITHUB_PATH + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} + key: ${{ matrix.platform }} + + - name: Build + shell: bash + run: cargo build --locked ${{ matrix.features }} + + - name: Tests + shell: bash + run: | + cargo test --locked ${{ matrix.features }} --lib + cargo test --locked --manifest-path ../vector-i18n/Cargo.toml + + # Animated pictures on DirectComposition visuals against the window's own drawing: a push whose + # message carries [media-parity]. Frozen frames, shot from the screen (DWM's composition, which + # a window capture misses), with the visuals and without; the diff and both shots are uploaded. + media-parity: + if: github.event_name == 'push' && contains(github.event.head_commit.message, '[media-parity]') + runs-on: windows-2022 + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + + - name: Prepare the runner + shell: pwsh + run: | + Set-MpPreference -DisableRealtimeMonitoring $true + $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE + echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> ../../../../t + key: windows-2022 + save-if: false + + # Whisper builds its Vulkan backend on x64 Windows, as in the build job. + - name: Cache Vulkan + id: vulkan-cache + uses: actions/cache@v5 + with: + path: C:\vcpkg\installed + key: vulkan-x64-windows-headers-loader-spirv-tools-glslc + + - name: Install Vulkan SDK + if: steps.vulkan-cache.outputs.cache-hit != 'true' + shell: pwsh + working-directory: . + run: | + vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows + Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + New-Item -ItemType Directory -Force -Path $vcpkgBin + Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force + + - name: Vulkan environment + shell: pwsh + run: | + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "$vcpkgBin" >> $env:GITHUB_PATH + + - name: Build + shell: bash + run: cargo build --locked --no-default-features --features devctl + + - name: Fixtures + shell: bash + run: | + pip install pillow numpy + python reference/gif_chats.py "$RUNNER_TEMP/fx" + + - name: Parity + shell: pwsh + run: | + Add-Type -AssemblyName System.Drawing + $exe = "$env:CARGO_TARGET_DIR\debug\vector-gpui.exe" + $fx = "$env:RUNNER_TEMP\fx" + $out = "$env:RUNNER_TEMP\parity" + $data = "$env:RUNNER_TEMP\vd" + $answer = "$env:TEMP\vector-devctl.json" + New-Item -ItemType Directory -Force -Path $out | Out-Null + $env:GPUI_MEDIA_LAYERS = "1" + $app = Start-Process -FilePath $exe -WorkingDirectory $fx -PassThru ` + -ArgumentList "--fixtures", "$fx\fixtures.json", "--data-dir", $data, "--size", "900x700" ` + -RedirectStandardOutput "$out\app.log" -RedirectStandardError "$out\app.err" + Start-Sleep 25 + function T($c) { & $exe --data-dir $data "dev:$c"; Start-Sleep -Milliseconds 400 } + function Shot($path) { + $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds + $bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height + $g = [System.Drawing.Graphics]::FromImage($bmp) + $g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size) + $bmp.Save($path, [System.Drawing.Imaging.ImageFormat]::Png) + $g.Dispose(); $bmp.Dispose() + } + Add-Type -AssemblyName System.Windows.Forms + $chats = @{ "1" = "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stmv"; "6" = "npub17jjvuhaxxs9rt2jakz6td5c6d7a2vpfr2erqmwc9xajhmqplt03q63stma" } + foreach ($n in "1", "6") { + T "chat:$($chats[$n])"; Start-Sleep 3; T "raise"; T "move:5,5" + foreach ($s in 0, -60, -200) { + T "idle:3600"; T "bottom"; Start-Sleep 1; T "scroll:$s"; Start-Sleep 4 + T "freeze:1"; Start-Sleep 2 + Shot "$out\on-$n-$s.png" + T "media:0"; Copy-Item $answer "$out\shown-$n-$s.json"; Start-Sleep 2 + Shot "$out\off-$n-$s.png" + T "media:1"; T "freeze:0"; Start-Sleep 1 + } + } + Stop-Process -Id $app.Id -Force + python reference/media_parity_diff.py $out + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: media-parity-windows + path: ${{ runner.temp }}/parity + + # Release builds to try the port on a Mac or a PC: a push whose message carries [package]. + # Thin LTO keeps a cold build near an hour; unsigned, so first launch needs the OS's override. + package: + if: inputs.release_tag || github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && contains(github.event.head_commit.message, '[package]')) + strategy: + fail-fast: false + matrix: + # The Tauri client's release targets, on the same runners: each of its installs has a + # bundle of its own kind to update to. macOS: both on the Intel image, Arm cross-compiled. + include: + - platform: macos-26-intel + target: aarch64-apple-darwin + out: aarch64-apple-darwin/release + features: '--target aarch64-apple-darwin --no-default-features --features video-static,tor,i2p' + ffmpeg: true + # ggml's native CPU probe would read the Intel host. + ggml_native: 'OFF' + - platform: macos-26-intel + target: x86_64-apple-darwin + out: x86_64-apple-darwin/release + features: '--target x86_64-apple-darwin --no-default-features --features video-static,tor,i2p' + ffmpeg: true + - platform: windows-2022 + target: x86_64-pc-windows-msvc + # The host's own target: a target directory level pushes whisper's Vulkan shader build past MAX_PATH. + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + # scripts/build-ffmpeg.sh has no Windows on Arm target yet: video attachments draw as files. + - platform: windows-11-arm + target: aarch64-pc-windows-msvc + out: release + features: '--no-default-features --features tor,i2p' + # The Tauri client's Linux release hosts: their glibc is the floor the packages run on. + - platform: ubuntu-22.04 + target: x86_64-unknown-linux-gnu + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + - platform: ubuntu-22.04-arm + target: aarch64-unknown-linux-gnu + out: release + features: '--no-default-features --features video-static,tor,i2p' + ffmpeg: true + runs-on: ${{ matrix.platform }} + env: + CARGO_PROFILE_RELEASE_LTO: thin + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: '16' + # A release's bundles take the Tauri client's names; a test package keeps its own. + VECTOR_RELEASE: ${{ inputs.release_tag && '1' || '' }} + defaults: + run: + working-directory: crates/vector-gpui + steps: + - uses: actions/checkout@v5 + + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ env.RUST_TOOLCHAIN }} + targets: ${{ matrix.target }} + + - name: Prepare the runner (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + Set-MpPreference -DisableRealtimeMonitoring $true + $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE + echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV + + # ring assembles its ARM64 Windows code with clang; MSVC's assembler can't. + - name: LLVM (Windows ARM) + if: matrix.platform == 'windows-11-arm' + shell: pwsh + run: | + if (-not (Test-Path "C:\Program Files\LLVM\bin\clang.exe")) { + if (Get-Command choco -ErrorAction SilentlyContinue) { choco install llvm -y --no-progress } + else { winget install --id LLVM.LLVM -e --silent --accept-package-agreements --accept-source-agreements } + } + echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH + + - name: Install dependencies (Linux) + if: startsWith(matrix.platform, 'ubuntu') + run: | + sudo apt-get update + sudo apt-get install -y libwebkit2gtk-4.1-dev libgtk-3-dev librsvg2-dev patchelf libasound2-dev \ + libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libxcb1-dev libfontconfig-dev libfreetype-dev \ + libvulkan-dev libssl-dev libzstd-dev clang cmake xdg-utils rpm + + # whisper builds its Vulkan backend on x64 Linux, which needs glslc, as in the Tauri release. + - name: Vulkan SDK (Linux x64) + if: matrix.platform == 'ubuntu-22.04' + run: | + wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc > /dev/null + sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-jammy.list https://packages.lunarg.com/vulkan/lunarg-vulkan-jammy.list + sudo apt-get update + sudo apt-get install -y vulkan-sdk + + - name: Cache FFmpeg + if: matrix.ffmpeg + id: ffmpeg-cache + uses: actions/cache@v5 + with: + path: src-tauri/native-deps/ffmpeg/${{ matrix.target }} + key: ffmpeg-${{ matrix.target }}-${{ hashFiles('scripts/build-ffmpeg.sh') }} + + - name: Build FFmpeg (macOS, Linux) + if: matrix.ffmpeg && !startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + working-directory: . + run: | + if [ "$RUNNER_OS" = macOS ]; then brew install nasm; else sudo apt-get install -y nasm; fi + scripts/build-ffmpeg.sh ${{ matrix.target }} + + - uses: ilammy/msvc-dev-cmd@v1 + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + + - uses: msys2/setup-msys2@v2 + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + with: + msystem: MSYS + path-type: inherit + install: make nasm diffutils + + - name: Build FFmpeg (Windows) + if: matrix.ffmpeg && startsWith(matrix.platform, 'windows') && steps.ffmpeg-cache.outputs.cache-hit != 'true' + shell: msys2 {0} + working-directory: . + run: scripts/build-ffmpeg.sh ${{ matrix.target }} + + - name: FFmpeg environment + if: matrix.ffmpeg + shell: bash + run: echo "FFMPEG_DIR=$GITHUB_WORKSPACE/src-tauri/native-deps/ffmpeg/${{ matrix.target }}" >> "$GITHUB_ENV" + + # Set only where the matrix asks: any value at all turns off whisper's x86-64-v3 pin. + - name: GGML_NATIVE + if: matrix.ggml_native + shell: bash + run: echo "GGML_NATIVE=${{ matrix.ggml_native }}" >> "$GITHUB_ENV" + + - name: macOS environment + if: startsWith(matrix.platform, 'macos') + run: | + echo "SDKROOT=$(xcrun --sdk macosx --show-sdk-path)" >> "$GITHUB_ENV" + + # Whisper transcribes on Vulkan on x64 Windows, as the desktop client does. + - name: Cache Vulkan (Windows x64) + if: matrix.platform == 'windows-2022' + id: vulkan-cache + uses: actions/cache@v5 + with: + path: C:\vcpkg\installed + key: vulkan-x64-windows-headers-loader-spirv-tools-glslc + + - name: Install Vulkan SDK (Windows x64) + if: matrix.platform == 'windows-2022' && steps.vulkan-cache.outputs.cache-hit != 'true' + shell: pwsh + working-directory: . + run: | + vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows + Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + New-Item -ItemType Directory -Force -Path $vcpkgBin + Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force + + - name: Vulkan environment (Windows x64) + if: matrix.platform == 'windows-2022' + shell: pwsh + run: | + $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" + echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV + echo "$vcpkgBin" >> $env:GITHUB_PATH + + - uses: Swatinem/rust-cache@v2 + with: + workspaces: crates/vector-gpui -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} + key: package-${{ matrix.target }} + + # In a developer prompt (the FFmpeg build's) rustc takes link.exe from PATH, where bash puts + # Git's coreutils link first; outside one it finds MSVC's itself. + - name: Build + shell: bash + run: | + unset VCINSTALLDIR + cargo build --release --locked ${{ matrix.features }} + + - name: Bundle (macOS) + if: startsWith(matrix.platform, 'macos') + run: scripts/bundle-macos.sh target/${{ matrix.out }}/vector-gpui "$RUNNER_TEMP/pkg" + + # NSIS for the Tauri client's NSIS installs, an MSI with its upgrade code for its MSI ones. + - name: Bundle (Windows) + if: startsWith(matrix.platform, 'windows') + shell: pwsh + run: | + $arch = if ("${{ matrix.target }}" -like "aarch64-*") { "arm64" } else { "x64" } + $prefix = if ($env:VECTOR_RELEASE -eq "1") { "Vector" } else { "Vector-GPUI" } + $pkg = "$env:RUNNER_TEMP\pkg" + New-Item -ItemType Directory -Force -Path $pkg | Out-Null + $exe = "$env:CARGO_TARGET_DIR\${{ matrix.out }}\vector-gpui.exe" + $version = (Select-String -Path Cargo.toml -Pattern '^version = "(.*)"' | Select-Object -First 1).Matches.Groups[1].Value + $icon = "$env:GITHUB_WORKSPACE\src-tauri\icons\icon.ico" + & "${env:ProgramFiles(x86)}\NSIS\makensis.exe" /V2 "/DSOURCE=$exe" "/DICON=$icon" "/DVERSION=$version" ` + "/DOUTFILE=$pkg\${prefix}_${version}_$arch-setup.exe" scripts\installer.nsi + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + + # MSI versions are numeric: a preview's number is the fourth field, as tauri-bundler writes it. + $msiVersion = $version -replace '-', '.' + $wix = if ($env:WIX) { "$env:WIX\bin" } else { "" } + if (-not $wix -or -not (Test-Path "$wix\candle.exe")) { + $wix = "$env:RUNNER_TEMP\wix" + Invoke-WebRequest -Uri "https://github.com/wixtoolset/wix3/releases/download/wix3141rtm/wix314-binaries.zip" -OutFile "$env:RUNNER_TEMP\wix.zip" + Expand-Archive "$env:RUNNER_TEMP\wix.zip" -DestinationPath $wix + } + $obj = "$env:RUNNER_TEMP\installer.wixobj" + & "$wix\candle.exe" -nologo -arch $arch "-dVersion=$msiVersion" "-dSource=$exe" "-dIcon=$icon" ` + -ext WixUIExtension -out $obj scripts\installer.wxs + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + & "$wix\light.exe" -nologo -ext WixUIExtension -cultures:en-us ` + -out "$pkg\${prefix}_${version}_${arch}_en-US.msi" $obj + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + Get-ChildItem $pkg + + - name: Bundle (Linux) + if: startsWith(matrix.platform, 'ubuntu') + env: + TOOLS: ${{ runner.temp }}/appimage-tools + run: | + scripts/bundle-appimage.sh target/${{ matrix.out }} "$RUNNER_TEMP/pkg" + scripts/bundle-linux-pkg.sh target/${{ matrix.out }} "$RUNNER_TEMP/pkg" + + - uses: actions/upload-artifact@v4 + with: + name: vector-gpui-${{ matrix.target }} + path: ${{ runner.temp }}/pkg + retention-days: 14 diff --git a/.github/workflows/languages.yaml b/.github/workflows/languages.yaml new file mode 100644 index 000000000..08e2b9cfa --- /dev/null +++ b/.github/workflows/languages.yaml @@ -0,0 +1,126 @@ +name: 'languages' +# Builds every language in crates/vector-i18n/locales, signs the index with the language key, +# and publishes both: packs to Blossom and to the `languages` release (by hash), then the index +# beside them and on Vector's relays. The GPUI client reads releases/download/languages/index.json, +# and the relays when it can't. +# +# Nothing is published until the VECTOR_LANGUAGES_KEY secret exists ("Publishing" in +# crates/vector-i18n/TRANSLATING.md). + +on: + push: + branches: [gpui, master] + paths: + - 'crates/vector-i18n/locales/**' + - 'crates/vector-i18n/src/**' + - '.github/workflows/languages.yaml' + pull_request: + paths: + - 'crates/vector-i18n/locales/**' + workflow_dispatch: + +permissions: + contents: write + +# Publishes from either branch write the same release, so they take turns. +concurrency: + group: languages-${{ github.event_name == 'pull_request' && github.ref || 'publish' }} + cancel-in-progress: false + +jobs: + # Every language against English, in the job summary: a broken message fails the check. + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@stable + - name: Coverage + working-directory: crates/vector-i18n + run: | + set -o pipefail + { echo '```'; cargo run --quiet --locked --bin vector-i18n -- status; echo '```'; } | tee -a "$GITHUB_STEP_SUMMARY" + + # Not gated on the check: a broken language keeps its last good pack, and the rest still ship. + publish: + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + env: + VECTOR_LANGUAGES_KEY: ${{ secrets.VECTOR_LANGUAGES_KEY }} + VECTOR_LANGUAGES_OLD_KEY: ${{ secrets.VECTOR_LANGUAGES_OLD_KEY }} + GH_TOKEN: ${{ github.token }} + steps: + - name: Is the language key set? + id: key + run: | + if [ -z "$VECTOR_LANGUAGES_KEY" ]; then + echo "::notice::VECTOR_LANGUAGES_KEY isn't set, so nothing is published." + echo "set=false" >> "$GITHUB_OUTPUT" + else + echo "set=true" >> "$GITHUB_OUTPUT" + fi + + - uses: actions/checkout@v5 + if: steps.key.outputs.set == 'true' + + - uses: dtolnay/rust-toolchain@stable + if: steps.key.outputs.set == 'true' + + - name: Build and sign + id: build + if: steps.key.outputs.set == 'true' + working-directory: crates/vector-i18n + run: | + mkdir -p ../../prev + gh release download languages --pattern index.json --dir ../../prev --repo "$GITHUB_REPOSITORY" || true + cargo build --release --features sign --bin vector-i18n + # A broken language keeps its last good pack listed; the job still fails at the end. + set +e + ./target/release/vector-i18n publish ../../out locales --previous ../../prev/index.json + echo "status=$?" >> "$GITHUB_OUTPUT" + + # Packs go up before the index that names them, so the index never points at a missing file. + - name: Packs to Blossom + if: steps.key.outputs.set == 'true' + continue-on-error: true + run: | + # The app's DEFAULT_BLOSSOM_SERVERS, which it tries in this order. + for f in out/*.vpack; do + for s in https://magnitude.vectorapp.io https://blossom.ditto.pub https://blossom.primal.net https://blossom.data.haus; do + auth=$(crates/vector-i18n/target/release/vector-i18n blossom-auth "$f") + if curl -fsS -o /dev/null -X PUT --data-binary @"$f" -H "Authorization: $auth" -H "Content-Type: application/octet-stream" "$s/upload"; then + echo "$s has $(basename "$f")" + else + echo "::warning::$s refused $(basename "$f")" + fi + done + done + + - name: Packs and index to the release + if: steps.key.outputs.set == 'true' + run: | + # `--prerelease` and `--latest=false` keep this off /releases/latest, which the updater reads. + if ! gh release view languages --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + gh release create languages --repo "$GITHUB_REPOSITORY" --prerelease --latest=false \ + --title 'Language packs' \ + --notes 'Signed language packs for the Vector app, published by CI. The app downloads and checks these itself.' + fi + have=$(gh release view languages --repo "$GITHUB_REPOSITORY" --json assets -q '.assets[].name') + for f in out/*.vpack; do + grep -qx "$(basename "$f")" <<< "$have" || gh release upload languages "$f" --repo "$GITHUB_REPOSITORY" + done + gh release upload languages out/index.json --clobber --repo "$GITHUB_REPOSITORY" + + - name: Index to relays + if: steps.key.outputs.set == 'true' + continue-on-error: true + run: | + pip install --quiet websockets + # The app's TRUSTED_RELAYS, where it looks when the release can't be reached. + python3 crates/vector-i18n/scripts/broadcast.py out/index.json \ + wss://jskitty.com/nostr wss://asia.vectorapp.io/nostr wss://nostr.computingcache.com wss://relay.ditto.pub + + - name: Broken translations + if: steps.key.outputs.set == 'true' && steps.build.outputs.status != '0' + run: | + echo "::error::A language has broken messages: its last good pack stays listed. See 'Build and sign'." + exit 1 diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index 06412adea..6acf87fa6 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -37,7 +37,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - VERSION=$(grep -m1 '^version' src-tauri/Cargo.toml | sed 's/version = "\(.*\)"/\1/') + VERSION=$(grep -m1 '^version' crates/vector-gpui/Cargo.toml | sed 's/version = "\(.*\)"/\1/') TAG="${TAG_PREFIX}v$VERSION" PRE=false [[ "$VERSION" == *-* ]] && PRE=true @@ -58,218 +58,6 @@ jobs: echo "id=$ID" >> $GITHUB_OUTPUT echo "prerelease=$PRE" >> $GITHUB_OUTPUT - publish-tauri: - needs: release - permissions: - contents: write - actions: write - strategy: - fail-fast: false - matrix: - # `cold`: no Rust cache. These finish well inside the Intel Mac build, and the repo's - # caches share 10 GB, so only the jobs that set the release's length keep one. macOS: - # both on the Intel image, Arm cross-compiled; GitHub's Arm macOS pools often go - # without a free runner, and the Intel one carries the same Xcode. - include: - - platform: 'macos-26-intel' # for Arm based macs (M1 and above). - args: '--target aarch64-apple-darwin' - ffmpeg: 'aarch64-apple-darwin' - # ggml's native CPU probe would read the Intel host. - ggml_native: 'OFF' - - platform: 'macos-26-intel' # for Intel based macs. - args: '--target x86_64-apple-darwin' - ffmpeg: 'x86_64-apple-darwin' - - platform: 'ubuntu-22.04' - args: '' - cold: true - - platform: 'windows-2022' - args: '' - ffmpeg: 'x86_64-pc-windows-msvc' - # ARM: native runners, Whisper on the CPU, and (for now) no video compression. - - platform: 'ubuntu-22.04-arm' - args: '' - cold: true - - platform: 'windows-11-arm' - args: '' - cold: true - - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v5 - - - name: setup node - uses: actions/setup-node@v5 - with: - node-version: lts/* - - - name: install Rust - uses: dtolnay/rust-toolchain@master - with: - toolchain: ${{ env.RUST_TOOLCHAIN }} - # Those targets are only used on macos runners so it's in an `if` to slightly speed up windows and linux builds. - targets: ${{ startsWith(matrix.platform, 'macos') && 'aarch64-apple-darwin,x86_64-apple-darwin' || '' }} - - # A throwaway runner: scanning every compiler write costs minutes and protects nothing. - # The target dir sits at the root of the workspace's drive (D:, the fast disk, on x64), - # keeping paths short for whisper's CMake build. /Brepro leaves the link time out of the - # executable, so a rebuild of one commit is identical. - - name: Prepare the runner (Windows) - if: startsWith(matrix.platform, 'windows') - shell: pwsh - run: | - Set-MpPreference -DisableRealtimeMonitoring $true - $drive = Split-Path -Qualifier $env:GITHUB_WORKSPACE - echo "CARGO_TARGET_DIR=$drive\t" >> $env:GITHUB_ENV - echo "CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_RUSTFLAGS=-C link-arg=/Brepro" >> $env:GITHUB_ENV - echo "CARGO_TARGET_AARCH64_PC_WINDOWS_MSVC_RUSTFLAGS=-C link-arg=/Brepro" >> $env:GITHUB_ENV - - # ring assembles its ARM64 Windows code with clang; MSVC's assembler can't. - - name: LLVM (Windows ARM) - if: matrix.platform == 'windows-11-arm' - shell: pwsh - run: | - if (-not (Test-Path "C:\Program Files\LLVM\bin\clang.exe")) { - if (Get-Command choco -ErrorAction SilentlyContinue) { choco install llvm -y --no-progress } - else { winget install --id LLVM.LLVM -e --silent --accept-package-agreements --accept-source-agreements } - } - echo "C:\Program Files\LLVM\bin" >> $env:GITHUB_PATH - & "C:\Program Files\LLVM\bin\clang.exe" --version - - - name: install dependencies (Linux) - if: startsWith(matrix.platform, 'ubuntu') - run: | - sudo apt-get update - sudo apt-get install -y libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libasound2-dev - - - name: Vulkan SDK (Linux x64) - if: matrix.platform == 'ubuntu-22.04' - run: | - wget -qO - https://packages.lunarg.com/lunarg-signing-key-pub.asc | sudo tee /etc/apt/trusted.gpg.d/lunarg.asc > /dev/null - sudo wget -qO /etc/apt/sources.list.d/lunarg-vulkan-jammy.list https://packages.lunarg.com/vulkan/lunarg-vulkan-jammy.list - sudo apt-get update - sudo apt-get install -y vulkan-sdk - - # vcpkg builds these from source (13 minutes). One fixed key: image updates move vcpkg's - # baseline weekly, and holding a single build keeps glslc's shader output the same. - - name: Cache Vulkan (Windows) - if: matrix.platform == 'windows-2022' - id: vulkan-cache - uses: actions/cache@v5 - with: - path: C:\vcpkg\installed - key: vulkan-x64-windows-headers-loader-spirv-tools-glslc - - - name: Install Vulkan SDK (Windows) - if: matrix.platform == 'windows-2022' && steps.vulkan-cache.outputs.cache-hit != 'true' - run: | - vcpkg install vulkan:x64-windows vulkan-headers:x64-windows vulkan-loader:x64-windows spirv-tools:x64-windows - Invoke-WebRequest -Uri "https://jskitty.com/glslc.exe" -OutFile "glslc.exe" - $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" - New-Item -ItemType Directory -Force -Path $vcpkgBin - Move-Item "glslc.exe" "$vcpkgBin\glslc.exe" -Force - - - name: Vulkan environment (Windows) - if: matrix.platform == 'windows-2022' - run: | - $vcpkgBin = "C:\vcpkg\installed\x64-windows\bin" - echo "VULKAN_SDK=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV - echo "CMAKE_PREFIX_PATH=C:\vcpkg\installed\x64-windows" >> $env:GITHUB_ENV - echo "$vcpkgBin" >> $env:GITHUB_PATH - & "$vcpkgBin\glslc.exe" --version - - # Video compression (VideoToolbox, Media Foundation) needs a selective FFmpeg; `npm run - # tauri` turns the feature on when it is present, so a failed FFmpeg build fails the job. - - name: Cache FFmpeg - if: matrix.ffmpeg - id: ffmpeg-cache - uses: actions/cache@v5 - with: - path: src-tauri/native-deps/ffmpeg/${{ matrix.ffmpeg }} - key: ffmpeg-${{ matrix.ffmpeg }}-${{ hashFiles('scripts/build-ffmpeg.sh') }} - - - name: Build FFmpeg (macOS) - if: startsWith(matrix.platform, 'macos') && steps.ffmpeg-cache.outputs.cache-hit != 'true' - run: | - brew install nasm - scripts/build-ffmpeg.sh ${{ matrix.ffmpeg }} - - - uses: ilammy/msvc-dev-cmd@v1 - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - - - uses: msys2/setup-msys2@v2 - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - with: - msystem: MSYS - path-type: inherit - install: make nasm diffutils - - - name: Build FFmpeg (Windows) - if: matrix.platform == 'windows-2022' && steps.ffmpeg-cache.outputs.cache-hit != 'true' - shell: msys2 {0} - run: scripts/build-ffmpeg.sh ${{ matrix.ffmpeg }} - - - name: install frontend dependencies - run: npm ci - - # Compiled dependencies, reused only where every input matches (source, flags, rustc), so a - # cached build links the same binary as a cold one. Written by release branches alone: a - # branch reads only its own caches and master's, never a pull request's. - - uses: Swatinem/rust-cache@v2 - if: ${{ !matrix.cold }} - id: rust-cache - with: - workspaces: src-tauri -> ${{ startsWith(matrix.platform, 'windows') && '../../../../t' || 'target' }} - key: ${{ matrix.ffmpeg || matrix.platform }} - save-if: ${{ github.ref_name == 'release' || github.ref_name == 'rehearsal' }} - - # Set only where the matrix asks: any value at all, even empty, turns off whisper's x86-64-v3 pin. - - name: GGML_NATIVE - if: matrix.ggml_native - run: echo "GGML_NATIVE=${{ matrix.ggml_native }}" >> "$GITHUB_ENV" - - - uses: tauri-apps/tauri-action@v0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} - TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} - with: - releaseId: ${{ needs.release.outputs.id }} - # latest.json is built once by `checksums`: every matrix job editing the shared asset raced. - includeUpdaterJson: false - # One more `tauri build` and upload on a failure: a flake this late would otherwise cost - # the whole job again. tauri.ci.conf.json and VECTOR_FRONTEND_ONCE keep the retry from - # recompiling the app. - retryAttempts: 1 - tauriScript: npm run tauri - args: ${{ matrix.args }} --config src-tauri/tauri.ci.conf.json ${{ needs.release.outputs.prerelease == 'true' && '--config src-tauri/tauri.preview.conf.json' || '' }} - - # The executable before bundling: two builds of one commit should print the same hash. - - name: Fingerprint the binary - shell: bash - run: | - dir="${CARGO_TARGET_DIR:-src-tauri/target}" - command -v cygpath > /dev/null && dir=$(cygpath -u "$dir") - for f in "$dir"/release/Vector "$dir"/release/Vector.exe "$dir"/*/release/Vector; do - [ -f "$f" ] && sha256sum "$f" - done - true - - # A moved key (lockfile, toolchain) saves a fresh cache as the job ends. Drop the one it - # replaces first: both would count against the 10 GB, and eviction takes the oldest-read. - - name: Drop the superseded Rust cache - if: steps.rust-cache.outputs.cache-hit == 'false' && (github.ref_name == 'release' || github.ref_name == 'rehearsal') - shell: bash - env: - GH_TOKEN: ${{ github.token }} - PREFIX: v0-rust-${{ matrix.ffmpeg || matrix.platform }}-${{ github.job }}- - run: | - gh api -X GET "repos/$GITHUB_REPOSITORY/actions/caches" -f ref="$GITHUB_REF" -f key="$PREFIX" \ - --jq '.actions_caches[] | "\(.id) \(.key)"' | - while read -r id key; do - echo "dropping $key" - gh api -X DELETE "repos/$GITHUB_REPOSITORY/actions/caches/$id" - done - # Android APKs: the ARM pair (and the universal fallback) alongside x86_64 for Chromebooks and # emulators, which ships as its own APK so the universal one doesn't grow. publish-android: @@ -391,8 +179,61 @@ jobs: # One file that vouches for every download: SHA256SUMS.txt over the release's assets, signed # with the updater key the app already trusts (minisign), and a build-provenance attestation per # asset so `gh attestation verify` ties each file to this workflow and commit. + # The desktop release: every target and installer type the Tauri client shipped, under its + # names, so each of its installs updates in place (scripts/updater-manifest.mjs). + build-gpui: + needs: release + permissions: + contents: read + uses: ./.github/workflows/gpui.yaml + with: + release_tag: ${{ needs.release.outputs.tag }} + + publish-gpui: + needs: [release, build-gpui] + runs-on: ubuntu-latest + permissions: + contents: write + env: + TAG: ${{ needs.release.outputs.tag }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v5 + with: + sparse-checkout: crates/vector-gpui/Cargo.toml + sparse-checkout-cone-mode: false + + # The app compares its own version against the manifest's, so a mismatch would loop updates. + - name: Version matches the release + run: | + V=$(grep -m1 '^version' crates/vector-gpui/Cargo.toml | sed 's/version = "\(.*\)"/\1/') + [ "${TAG#"${TAG_PREFIX}"v}" = "$V" ] || { echo "vector-gpui is $V, the release is $TAG"; exit 1; } + + - uses: actions/download-artifact@v4 + with: + pattern: vector-gpui-* + path: pkg + merge-multiple: true + + # Test packages' zip and the DMG are downloads, not updates: no signature, and no zip. + - name: Sign with the updater key + env: + TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }} + TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY_PASSWORD }} + run: | + rm -f pkg/*.zip + ls -l pkg + for f in pkg/*; do + case "$f" in *.dmg) continue ;; esac + npx --yes @tauri-apps/cli@2.12.2 signer sign "$f" + done + + - name: Upload to the release + run: gh release upload "$TAG" pkg/* --clobber --repo "$GITHUB_REPOSITORY" + checksums: - needs: [release, publish-tauri, publish-android, publish-android-fdroid] + needs: [release, publish-gpui, publish-android, publish-android-fdroid] + if: ${{ !cancelled() && needs.publish-gpui.result == 'success' && needs.publish-android.result == 'success' && needs.publish-android-fdroid.result == 'success' }} runs-on: ubuntu-latest permissions: contents: write diff --git a/CLAUDE.md b/CLAUDE.md index 36e710d17..1aa669e74 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,6 +110,14 @@ Live end-to-end checks of SDK bots against real relays (`cargo run -p vector-lab scenario runs its roles as child processes, throwaway identities and a throwaway Community, and exits non-zero on a failed check. Run it before a crates release. +### Vector Translate (`crates/vector-translate/`) + +On-device message translation for the GPUI client: fastText `lid.176` language ID (a Rust port, +checked against fastText's own output in `tests/models.rs`), Firefox Translations models run by +a vendored fxtranslate (`vendor/fxtranslate/VECTOR.md` lists the changes), the pinned catalogue +(`scripts/catalog.py` regenerates it) and the models folder. No network: the client downloads. +Outgoing messages are never translated; each reader translates the original. + ### Vector Web (`crates/vector-web/`, `web/`) The same frontend in a browser, over vector-core compiled to wasm32 in a dedicated worker @@ -157,6 +165,13 @@ Frontend communicates with backend via `window.__TAURI__.core.invoke()`. ## Key Patterns +### Never redo work that can be cached cheaply + +Don't repeat a computation or a read (DB, disk, network) when its result could be kept at a small +memory cost and a cheap lookup. A boot once ran the same settings row 9,200 times; repeats like that +add up to whole frames of CPU and pool contention. Keep the copy on the session and drop it when +its source is written (see `db::changes` for read copies the database's own write hooks invalidate). + ### 🚨 Multi-account safety — read this BEFORE writing code that touches STATE, the DB, or relays Vector supports N accounts per install, and a swap can happen at **any await point**: mid-fetch, diff --git a/crates/Cargo.lock b/crates/Cargo.lock index d7c8c4e19..4b31b6458 100644 --- a/crates/Cargo.lock +++ b/crates/Cargo.lock @@ -8212,6 +8212,7 @@ dependencies = [ "js-sys", "libc", "libcrux-ml-kem", + "memchr", "ml-kem", "negentropy", "noq-proto", diff --git a/crates/Cargo.toml b/crates/Cargo.toml index bc2b86cb9..9e340f576 100644 --- a/crates/Cargo.toml +++ b/crates/Cargo.toml @@ -1,7 +1,7 @@ [workspace] members = ["vector-calls", "vector-core", "vector-cli", "concord-cli", "vector-agent", "vector-sdk", "vector-media", "vector-web", "vector-push", "vector-pusher", "vector-lab"] # Vendored crates (patched in from src-tauri) are packages of their own, not members. -exclude = ["vendor"] +exclude = ["vendor", "vector-gpui"] resolver = "2" # Dependencies compile OPTIMIZED even in dev/test; our own crates stay unoptimized diff --git a/crates/vector-core/Cargo.toml b/crates/vector-core/Cargo.toml index bcb301443..4b41a4f07 100644 --- a/crates/vector-core/Cargo.toml +++ b/crates/vector-core/Cargo.toml @@ -53,7 +53,7 @@ bitcoin_hashes = { version = "1.2", default-features = false, features = ["std", bip39 = { version = "2.2.2", features = ["rand"] } # Database -rusqlite = { version = "0.38", features = ["bundled", "fallible_uint"] } +rusqlite = { version = "0.38", features = ["bundled", "fallible_uint", "trace", "hooks"] } # Async (tokio's full feature set is native-only; see the wasm32 target table) tokio = { version = "1.49.0", features = ["sync", "time", "io-util", "macros", "rt"] } @@ -82,6 +82,7 @@ ghash = "0.6" argon2 = "0.5.3" sha2 = "0.10.9" unicode-normalization = "0.1" +memchr = "2" # HKDF-SHA256 for the Community protocol's frozen key-derivation convention # (GROUP_PROTOCOL.md §14). Audited RustCrypto crate rather than a hand-rolled # construction, since the derivation is wire-immutable. @@ -141,7 +142,7 @@ tor-guardmgr = { version = "0.45", default-features = false, features = ["bridge tokio-util = { version = "0.7", features = ["compat"], optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -tokio = { version = "1.49.0", features = ["net", "rt-multi-thread"] } +tokio = { version = "1.49.0", features = ["net", "rt-multi-thread", "fs"] } # The transport's relay socket (`transport::ws`): the same SOCKS client, TCP connect and # WebSocket upgrade nostr-sdk's default transport uses (all already in the tree through it), # so the Direct path stays byte-identical. TLS features unify with async-wsocket's ring roots. diff --git a/crates/vector-core/benches/core/main.rs b/crates/vector-core/benches/core/main.rs index 3be81095b..7ed66ca0f 100644 --- a/crates/vector-core/benches/core/main.rs +++ b/crates/vector-core/benches/core/main.rs @@ -12,10 +12,42 @@ mod compact; mod db_reads; mod parse; mod pool; +mod search; + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicUsize, Ordering}; use nostr_sdk::prelude::{Keys, ToBech32}; use vector_core::crypto::guarded_key::bench as vault; +/// Live heap bytes, for the benchmarks that report what a structure holds. +struct Counting; + +static LIVE: AtomicUsize = AtomicUsize::new(0); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + LIVE.fetch_add(l.size(), Ordering::Relaxed); + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + LIVE.fetch_sub(l.size(), Ordering::Relaxed); + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, new: usize) -> *mut u8 { + LIVE.fetch_add(new, Ordering::Relaxed); + LIVE.fetch_sub(l.size(), Ordering::Relaxed); + unsafe { System.realloc(p, l, new) } + } +} + +#[global_allocator] +static ALLOC: Counting = Counting; + +pub fn live_bytes() -> usize { + LIVE.load(Ordering::Relaxed) +} + const ALL: &[(&str, fn())] = &[ ("compact::messages", compact::messages), ("compact::profile_lookup", compact::profile_lookup), @@ -38,6 +70,7 @@ const ALL: &[(&str, fn())] = &[ ("crypto::chacha20_raw", parse::chacha20_raw), ("crypto::nip44_decrypt", parse::nip44_decrypt), ("crypto::chacha20_backends", parse::chacha20_backends), + ("search::scan", search::scan), ("profile::processor", vector_core::profile::sync::bench::processor), ("vault::designs", vault::designs), ("vault::set_sources", vault::set_sources), diff --git a/crates/vector-core/benches/core/search.rs b/crates/vector-core/benches/core/search.rs new file mode 100644 index 000000000..5c3df5b28 --- /dev/null +++ b/crates/vector-core/benches/core/search.rs @@ -0,0 +1,73 @@ +//! Message search: building the corpus, then the scans a keystroke runs. + +use std::time::Instant; +use vector_core::search::{Corpus, Filter, Has, Query, Record}; + +const WORDS: &[&str] = &[ + "the", "build", "relay", "lunch", "tomorrow", "café", "release", "voice", "channel", "bug", + "fixed", "photo", "meeting", "deploy", "東京", "会議", "night", "cats", "music", "invoice", +]; + +/// 200,000 messages of 12 to 30 words across 300 chats. +pub fn scan() { + const N: usize = 200_000; + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let records: Vec = (0..N) + .map(|i| { + let n = 12 + (next() % 19) as usize; + let text = (0..n).map(|_| WORDS[(next() % WORDS.len() as u64) as usize]).collect::>().join(" "); + let files = if i % 25 == 0 { vec![("jpg".to_string(), format!("IMG_{i}.jpg"))] } else { Vec::new() }; + Record { + chat: format!("chat{}", next() % 300), + id: format!("{i:064x}"), + author: Some(format!("npub1{:0>58}", next() % 500)), + mine: i % 7 == 0, + at: 1_800_000_000_000 - i as u64 * 1000, + text, + files, + ..Default::default() + } + }) + .collect(); + let before = crate::live_bytes(); + let t = Instant::now(); + let mut corpus = Corpus::new(); + for r in &records { + corpus.push(r, &r.text); + } + let took = t.elapsed(); + corpus.shrink(); + println!("build {:>9.1} ms ({} messages)", took.as_secs_f64() * 1e3, corpus.len()); + println!("held {:>9.1} MB", (crate::live_bytes() - before) as f64 / 1e6); + + let cases: &[(&str, &str, Filter)] = &[ + ("rare word", "invoice deploy", Filter::default()), + ("common word", "the", Filter::default()), + ("no match", "zzzzzz", Filter::default()), + ("cjk", "会議", Filter::default()), + ("phrase", "\"lunch tomorrow\"", Filter::default()), + ("has:image", "", Filter { has: Has::IMAGE, ..Default::default() }), + ("in: + word", "relay", Filter { chats: vec!["chat7".into()], ..Default::default() }), + ("oldest", "cats", Filter { oldest: true, ..Default::default() }), + ("from:", "", Filter { from: vec![format!("npub1{:0>58}", 7)], ..Default::default() }), + ("from: + word", "lunch", Filter { from: vec![format!("npub1{:0>58}", 7)], ..Default::default() }), + ("a day", "", Filter { after: Some(1_800_000_000_000 - 86_400_000), before: Some(1_800_000_000_000), ..Default::default() }), + ("word + day", "the", Filter { after: Some(1_800_000_000_000 - 86_400_000), before: Some(1_800_000_000_000), ..Default::default() }), + ]; + for (name, q, f) in cases { + let query = Query::parse(q); + let runs = 20; + let t = Instant::now(); + let mut total = 0; + for _ in 0..runs { + total = corpus.search(&query, f, 200).total; + } + println!("{name:<12} {:>7.2} ms ({total} matches)", t.elapsed().as_secs_f64() * 1e3 / runs as f64); + } +} diff --git a/crates/vector-core/examples/mem_census.rs b/crates/vector-core/examples/mem_census.rs index f29b74d67..8aa823b5a 100644 --- a/crates/vector-core/examples/mem_census.rs +++ b/crates/vector-core/examples/mem_census.rs @@ -208,7 +208,7 @@ fn main() { if rng.pct(3) { let title = rng.text(20, 70); let desc = rng.text(60, 200); - m.preview_metadata = Some(SiteMetadata { + m.preview_metadata = Some(Box::new(SiteMetadata { domain: "github.com".into(), og_title: Some(title.clone()), og_description: Some(desc.clone()), @@ -218,7 +218,7 @@ fn main() { title: Some(title), description: Some(desc), favicon: Some("https://github.githubassets.com/favicons/favicon.svg".into()), - }); + })); } if rng.pct(2) { let first = rng.text(8, 120); diff --git a/crates/vector-core/src/boot_probe.rs b/crates/vector-core/src/boot_probe.rs new file mode 100644 index 000000000..06805fdf7 --- /dev/null +++ b/crates/vector-core/src/boot_probe.rs @@ -0,0 +1,290 @@ +//! A startup census in vector.log: what a cold boot fans out to (clients, sockets, reads, CPU). +//! Persisted like a network failure because the log file keeps nothing quieter. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; + +/// Plane connections built: authed per plane key, and open per relay. +pub static PLANE_DIALS: AtomicU64 = AtomicU64::new(0); +pub static OPEN_DIALS: AtomicU64 = AtomicU64::new(0); +/// Relay frames that reached a community read's listener, its own or another read's. +pub static READ_FRAMES: AtomicU64 = AtomicU64::new(0); +/// Events those reads kept. +pub static READ_KEPT: AtomicU64 = AtomicU64::new(0); +/// Community reads listening on a relay now, and the most at once. +pub static READERS: AtomicU64 = AtomicU64::new(0); +pub static READERS_PEAK: AtomicU64 = AtomicU64::new(0); + +/// Database connections taken, and the microseconds spent waiting for them. +pub static DB_READS: AtomicU64 = AtomicU64::new(0); +pub static DB_WRITES: AtomicU64 = AtomicU64::new(0); +pub static DB_WAIT_US: AtomicU64 = AtomicU64::new(0); +/// Of that wait, the writers' (queued behind the one write connection). +pub static DB_WRITE_WAIT_US: AtomicU64 = AtomicU64::new(0); +/// Milliseconds the reader's own fetches spent dialling and authenticating plane connections, +/// waiting for a read slot on an open plane socket, and waiting for the write connection. +pub static FOREGROUND_DIAL_MS: AtomicU64 = AtomicU64::new(0); +pub static FOREGROUND_SLOT_MS: AtomicU64 = AtomicU64::new(0); +pub static FOREGROUND_WRITE_WAIT_MS: AtomicU64 = AtomicU64::new(0); + +/// The reader's own fetch phases so far: (dialling, read slots, write waits) in milliseconds. +pub fn foreground_phases() -> (u64, u64, u64) { + (FOREGROUND_DIAL_MS.load(Relaxed), FOREGROUND_SLOT_MS.load(Relaxed), FOREGROUND_WRITE_WAIT_MS.load(Relaxed)) +} + +/// Connections opened past the pools, and page caches released on a connection's return. +pub static DB_PASSING_READS: AtomicU64 = AtomicU64::new(0); +pub static DB_OWN_WRITES: AtomicU64 = AtomicU64::new(0); +pub static DB_TRIMS: AtomicU64 = AtomicU64::new(0); + +/// Whether the census is running: what only it reads is gathered only then. +static OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Each statement's runs, total and longest microseconds, while the census runs. +type Statements = std::collections::HashMap; +static STATEMENTS: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// SQLite's word on a statement it finished: its text (parameters unbound) and its run time. +pub fn note_sql(sql: &str, took: std::time::Duration) { + if !OPEN.load(Relaxed) { + return; + } + let key: String = sql.split_whitespace().collect::>().join(" ").chars().take(100).collect(); + let us = took.as_micros() as u64; + let mut all = STATEMENTS.lock().unwrap_or_else(|e| e.into_inner()); + let e = all.get_or_insert_with(Default::default).entry(key).or_default(); + e.0 += 1; + e.1 += us; + e.2 = e.2.max(us); +} + +#[cfg(test)] +/// How long `f` took and how many statements it ran. +pub(crate) fn counting_statements(f: impl FnOnce()) -> (std::time::Duration, u64) { + *STATEMENTS.lock().unwrap() = None; + OPEN.store(true, Relaxed); + let t = web_time::Instant::now(); + f(); + let took = t.elapsed(); + OPEN.store(false, Relaxed); + let runs = STATEMENTS.lock().unwrap().take().map_or(0, |m| m.values().map(|v| v.0).sum()); + (took, runs) +} + +/// Settings rows written while the census runs, by family: the key with its ids dropped. +static SETTING_WRITES: std::sync::Mutex>> = std::sync::Mutex::new(None); + +pub fn note_setting_write(key: &str) { + if !OPEN.load(Relaxed) { + return; + } + let family: String = key.split([':', '_']).filter(|p| !p.is_empty() && !p.bytes().all(|b| b.is_ascii_hexdigit() || b.is_ascii_digit())).collect::>().join("_"); + *SETTING_WRITES.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(Default::default).entry(family).or_default() += 1; +} + +/// The five most written settings families. +fn setting_writes() -> String { + let all = SETTING_WRITES.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = all.as_ref() else { return String::new() }; + let mut v: Vec<_> = m.iter().collect(); + v.sort_by(|a, b| b.1.cmp(a.1)); + v.iter().take(5).map(|(k, n)| format!(" {k} x{n}")).collect() +} + +/// The five statements that ran longest in all. +fn costliest() -> String { + let all = STATEMENTS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(m) = all.as_ref() else { return String::new() }; + let mut v: Vec<_> = m.iter().collect(); + v.sort_by(|a, b| b.1 .1.cmp(&a.1 .1)); + v.iter().take(5).map(|(sql, (n, us, max))| format!(" [x{n} {}ms max {}ms: {sql}]", us / 1000, max / 1000)).collect() +} + +/// Connections held past `SLOW_HOLD`, by where they were taken: (writer, file, line) to count +/// and total milliseconds. +type Holds = std::collections::HashMap<(bool, &'static str, u32), (u64, u64)>; +static SLOW_HOLDS: std::sync::Mutex> = std::sync::Mutex::new(None); + +pub fn note_slow_hold(writer: bool, at: &'static std::panic::Location<'static>, held: std::time::Duration) { + let mut holds = SLOW_HOLDS.lock().unwrap_or_else(|e| e.into_inner()); + let e = holds.get_or_insert_with(Default::default).entry((writer, at.file(), at.line())).or_default(); + e.0 += 1; + e.1 += held.as_millis() as u64; +} + +/// The three call sites that held connections longest in all. +fn slowest() -> String { + let holds = SLOW_HOLDS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(h) = holds.as_ref() else { return String::new() }; + let mut v: Vec<_> = h.iter().collect(); + v.sort_by(|a, b| b.1 .1.cmp(&a.1 .1)); + v.iter() + .take(3) + .map(|((w, f, l), (n, ms))| format!(" {}{}:{} x{} {}ms", if *w { "w " } else { "" }, f.rsplit('/').next().unwrap_or(f), l, n, ms)) + .collect() +} + +pub fn note_db(c: &AtomicU64, asked: web_time::Instant) { + note(c); + let us = asked.elapsed().as_micros() as u64; + DB_WAIT_US.fetch_add(us, Relaxed); + if std::ptr::eq(c, &DB_WRITES) { + DB_WRITE_WAIT_US.fetch_add(us, Relaxed); + if crate::community::cache::is_foreground() { + FOREGROUND_WRITE_WAIT_MS.fetch_add(us / 1000, Relaxed); + } + } +} + +/// A read listening until dropped. +pub struct Reader; + +impl Reader { + pub fn new() -> Self { + let now = READERS.fetch_add(1, Relaxed) + 1; + READERS_PEAK.fetch_max(now, Relaxed); + Reader + } +} + +impl Drop for Reader { + fn drop(&mut self) { + READERS.fetch_sub(1, Relaxed); + } +} + +/// Community reads asked of relays. +pub static FETCHES: AtomicU64 = AtomicU64::new(0); + +/// When the latest login began, for the census and the focused pages. +static START: std::sync::Mutex> = std::sync::Mutex::new(None); +/// The census running now: a login's census supersedes the one before, which stops quietly. +static RUN: AtomicU64 = AtomicU64::new(0); + +fn start() -> Option { + *START.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// A channel opened in the census window has its newest page: how long that took, and since login. +/// `dialled`: connections dialled while it was read, which it may have waited on; `phases`, how +/// long the reader's own fetches spent meanwhile dialling, waiting for a read slot and waiting +/// for the write connection (see [`foreground_phases`]). +pub fn note_focused(took: std::time::Duration, dialled: u64, phases: (u64, u64, u64)) { + let Some(start) = start() else { return }; + if start.elapsed() > std::time::Duration::from_secs(300) { + return; + } + crate::log_net_fail!( + "[boot-probe] focused page in {} ms, {} ms after login, plane dials {} ({} during it), its own: dialling {} ms, read slots {} ms, write waits {} ms", + took.as_millis(), + start.elapsed().as_millis(), + PLANE_DIALS.load(Relaxed), + dialled, + phases.0, + phases.1, + phases.2 + ); +} + +/// Plane and open connections dialled so far. +pub fn dials() -> u64 { + PLANE_DIALS.load(Relaxed) + OPEN_DIALS.load(Relaxed) +} + +pub fn note(c: &AtomicU64) { + c.fetch_add(1, Relaxed); +} + +/// Planes dialled, told apart: a dial of one already dialled is the pool's churn. +static PLANES_SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + +pub fn note_plane(key: &str) { + note(&PLANE_DIALS); + let mut seen = PLANES_SEEN.lock().unwrap_or_else(|e| e.into_inner()); + seen.get_or_insert_with(Default::default).insert(key.to_string()); +} + +fn planes_seen() -> usize { + PLANES_SEEN.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map_or(0, |s| s.len()) +} + +#[cfg(not(target_arch = "wasm32"))] +/// One line every 10 s for the first 5 minutes after login. +pub async fn run() { + let start = web_time::Instant::now(); + *START.lock().unwrap_or_else(|e| e.into_inner()) = Some(start); + let run = RUN.fetch_add(1, Relaxed) + 1; + OPEN.store(true, Relaxed); + let mut last = rusage(); + for _ in 0..30 { + crate::rt::time::sleep(std::time::Duration::from_secs(10)).await; + if RUN.load(Relaxed) != run { + return; + } + let (pooled, open, mut clients) = crate::community::transport::plane_census(); + if let Some(main) = crate::state::nostr_client() { + clients.push(main); + } + let (mut handles, mut connected) = (0usize, 0usize); + for c in &clients { + for r in c.relays().all().await.values() { + handles += 1; + connected += usize::from(r.status() == nostr_sdk::prelude::RelayStatus::Connected); + } + } + let now = rusage(); + let tasks = tokio::runtime::Handle::try_current().map_or(0, |h| h.metrics().num_alive_tasks()); + crate::log_net_fail!( + "[boot-probe] t={}s clients={} (pooled {} open {}) relays={} connected={} dials plane={} ({} distinct) open={} fetches={} frames {} kept {} readers peak {} db r {} w {} wait {}ms (writers {}ms) passing {} own-writes {} trims {} slow[{}] sql[{}] settings[{}] tasks={} cpu+10s user={:.1}s sys={:.1}s csw={}", + start.elapsed().as_secs(), + clients.len(), + pooled, + open, + handles, + connected, + PLANE_DIALS.load(Relaxed), + planes_seen(), + OPEN_DIALS.load(Relaxed), + FETCHES.load(Relaxed), + READ_FRAMES.load(Relaxed), + READ_KEPT.load(Relaxed), + READERS_PEAK.load(Relaxed), + DB_READS.load(Relaxed), + DB_WRITES.load(Relaxed), + DB_WAIT_US.load(Relaxed) / 1000, + DB_WRITE_WAIT_US.load(Relaxed) / 1000, + DB_PASSING_READS.load(Relaxed), + DB_OWN_WRITES.load(Relaxed), + DB_TRIMS.load(Relaxed), + slowest(), + costliest(), + setting_writes(), + tasks, + now.0 - last.0, + now.1 - last.1, + now.2.saturating_sub(last.2), + ); + last = now; + } + if RUN.load(Relaxed) == run { + OPEN.store(false, Relaxed); + *STATEMENTS.lock().unwrap_or_else(|e| e.into_inner()) = None; + *SETTING_WRITES.lock().unwrap_or_else(|e| e.into_inner()) = None; + } +} + +#[cfg(all(unix, not(target_arch = "wasm32")))] +/// This process's user and system CPU seconds and context switches so far. +fn rusage() -> (f64, f64, u64) { + let mut u: libc::rusage = unsafe { std::mem::zeroed() }; + // SAFETY: getrusage fills the struct it is given. + if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut u) } != 0 { + return (0., 0., 0); + } + let secs = |t: libc::timeval| t.tv_sec as f64 + t.tv_usec as f64 / 1e6; + (secs(u.ru_utime), secs(u.ru_stime), (u.ru_nvcsw + u.ru_nivcsw) as u64) +} + +#[cfg(all(not(unix), not(target_arch = "wasm32")))] +fn rusage() -> (f64, f64, u64) { + (0., 0., 0) +} diff --git a/crates/vector-core/src/calls/session.rs b/crates/vector-core/src/calls/session.rs index b4d849e3f..e25ba14cf 100644 --- a/crates/vector-core/src/calls/session.rs +++ b/crates/vector-core/src/calls/session.rs @@ -266,6 +266,16 @@ fn with_call(f: impl FnOnce(&mut Call) -> R) -> Option { guard.as_mut().map(f) } +/// The live call's (mic, peer) levels as they stand: for meters a client draws every frame, +/// between the ten-a-second events. +pub fn levels_now() -> Option<(f32, f32)> { + with_call(|c| c.media.as_ref().map(|m| { + let s = m.stats(); + (s.mic_level(), s.peer_level()) + })) + .flatten() +} + fn with_call_id(id: &str, f: impl FnOnce(&mut Call) -> R) -> Option { let mut guard = slot().lock().unwrap_or_else(|e| e.into_inner()); match guard.as_mut() { diff --git a/crates/vector-core/src/calls/voice.rs b/crates/vector-core/src/calls/voice.rs index 73b311cd0..ce19f3c6b 100644 --- a/crates/vector-core/src/calls/voice.rs +++ b/crates/vector-core/src/calls/voice.rs @@ -998,6 +998,25 @@ fn refresh_awake(v: &Voice) { *slot = Some((level, hold)); } +/// Each linked member's level by public key (hex), and ours under an empty key, read as it +/// stands: for meters a client draws every frame, between the five-a-second events. +pub fn levels_now() -> Vec<(String, f32)> { + let Some(v) = live() else { return Vec::new() }; + let Some(engine) = v.engine() else { return Vec::new() }; + let levels = engine.levels(); + if levels.len() < 2 { + return levels.into_iter().map(|(_, l)| (String::new(), l)).collect(); + } + let present = presence::present(&v.channel_hex, now_ms()); + levels + .into_iter() + .filter_map(|(ep, l)| match ep { + None => Some((String::new(), l)), + Some(ep) => present.iter().find(|p| p.endpoint == Some(ep)).map(|p| (p.author.to_hex(), l)), + }) + .collect() +} + /// Who is speaking, five times a second while there is audio to show it. async fn levels(v: Arc) { loop { diff --git a/crates/vector-core/src/community/attachments.rs b/crates/vector-core/src/community/attachments.rs index 7294c89ea..63a7181d1 100644 --- a/crates/vector-core/src/community/attachments.rs +++ b/crates/vector-core/src/community/attachments.rs @@ -31,6 +31,10 @@ pub fn attachment_to_imeta(att: &Attachment) -> Tag { if !att.name.is_empty() { fields.push(format!("name {}", att.name)); } + // NIP-92 readers (Armada) blur on `content-warning`; Vector reads the name's prefix. + if is_spoiler_name(&att.name) { + fields.push("content-warning spoiler".to_string()); + } if let Some(meta) = &att.img_meta { if !meta.thumbhash.is_empty() { fields.push(format!("thumb {}", meta.thumbhash)); @@ -49,6 +53,12 @@ pub fn attachment_to_imeta(att: &Attachment) -> Tag { Tag::custom(IMETA, fields) } +const SPOILER_PREFIX: &str = "SPOILER_"; + +fn is_spoiler_name(name: &str) -> bool { + name.get(..SPOILER_PREFIX.len()).is_some_and(|p| p.eq_ignore_ascii_case(SPOILER_PREFIX)) +} + /// Read a single `key value` field from an `imeta` tag's entries (value is everything /// after the first space, so spaces in the value are preserved). fn field<'a>(entries: &'a [String], key: &str) -> Option<&'a str> { @@ -93,7 +103,7 @@ pub fn attachment_from_imeta(tag: &Tag, download_dir: &Path) -> Option Option().ok()).unwrap_or(0); // Vector stamps the plaintext sha256 as `ox`; NIP-92 uses `x`. Either serves @@ -110,7 +128,10 @@ pub fn attachment_from_imeta(tag: &Tag, download_dir: &Path) -> Option().ok()?, h.parse::().ok()?)) @@ -397,6 +418,28 @@ mod tests { assert_eq!(field(&["url".to_string()], "url"), None); } + #[test] + fn a_spoiler_travels_as_a_content_warning_too() { + let dir = std::env::temp_dir(); + let tag = attachment_to_imeta(&sample("SPOILER_x.png", "png", false)); + assert!(tag.as_slice().iter().any(|e| e == "content-warning spoiler")); + let plain = attachment_to_imeta(&sample("x.png", "png", false)); + assert!(!plain.as_slice().iter().any(|e| e.starts_with("content-warning"))); + let foreign = Tag::custom(IMETA, ["url https://b.example/f.png", "m image/png", "name f.png", "content-warning"]); + assert_eq!(attachment_from_imeta(&foreign, &dir).unwrap().name, "SPOILER_f.png"); + let nameless = Tag::custom(IMETA, ["url https://b.example/g", "m image/png", "content-warning nsfw"]); + assert_eq!(attachment_from_imeta(&nameless, &dir).unwrap().name, "SPOILER_file.png"); + } + + #[test] + fn a_thumb_url_is_not_read_as_a_thumbhash() { + let dir = std::env::temp_dir(); + let tag = Tag::custom(IMETA, ["url https://b.example/f.png", "m image/png", "dim 10x10", "thumb https://b.example/t.png"]); + assert!(attachment_from_imeta(&tag, &dir).unwrap().img_meta.is_none()); + let tag = Tag::custom(IMETA, ["url https://b.example/f.png", "m image/png", "dim 10x10", "thumbhash 1QcSHQRnh493V4dIh4eXh1h4kJUI"]); + assert_eq!(attachment_from_imeta(&tag, &dir).unwrap().img_meta.unwrap().thumbhash, "1QcSHQRnh493V4dIh4eXh1h4kJUI"); + } + #[test] fn multiple_imeta_tags_parse_in_order() { let dir = std::env::temp_dir(); diff --git a/crates/vector-core/src/community/cache.rs b/crates/vector-core/src/community/cache.rs index 83365b3d8..1f6fb1336 100644 --- a/crates/vector-core/src/community/cache.rs +++ b/crates/vector-core/src/community/cache.rs @@ -1,5 +1,6 @@ -//! Per-account RAM state for Community sync: the in-flight page claims. Keyed by this -//! account's channel ids, so it lives on the account's session and goes when that does. +//! Per-account RAM state for Community sync: the in-flight page claims and the foreground gate. +//! Keyed by this account's channel ids, so it lives on the account's session and goes when that +//! does. use std::collections::HashSet; use std::sync::{Arc, Mutex}; @@ -41,10 +42,95 @@ pub fn claim_page_fetch(channel_id: &str, older: bool) -> Option Some(PageFetchClaim { set, key: Some(key) }) } +struct ForegroundKey; + +#[derive(Default)] +struct ForegroundGate { + running: std::sync::atomic::AtomicUsize, + done: tokio::sync::Notify, +} + +fn foreground_gate() -> Arc { + crate::db::current_session().scoped::() +} + +/// A fetch the reader is waiting on (the newest page of the channel on screen): background +/// channel walks hold off until it ends. Released when dropped. +pub struct Foreground(Arc); + +impl Drop for Foreground { + fn drop(&mut self) { + if self.0.running.fetch_sub(1, std::sync::atomic::Ordering::AcqRel) == 1 { + self.0.done.notify_waiters(); + } + } +} + +/// Marks a foreground fetch running until the guard drops. +pub fn foreground() -> Foreground { + let gate = foreground_gate(); + gate.running.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + Foreground(gate) +} + +tokio::task_local! { + static FOREGROUND_TASK: (); +} + +/// Runs `fut` as the reader's own fetch: what it dials skips the queue background sync waits in. +pub async fn in_foreground(fut: F) -> F::Output { + FOREGROUND_TASK.scope((), fut).await +} + +/// Whether this task is the reader's own fetch. +pub fn is_foreground() -> bool { + FOREGROUND_TASK.try_with(|_| ()).is_ok() +} + +/// The longest a background walk waits on foreground fetches: one that hangs can't stall the rest. +const FOREGROUND_WAIT: std::time::Duration = std::time::Duration::from_secs(15); + +/// Waits, before a background channel walk, until no foreground fetch is running. +pub async fn after_foreground() { + let gate = foreground_gate(); + let _ = crate::rt::time::timeout(FOREGROUND_WAIT, async { + loop { + let done = gate.done.notified(); + if gate.running.load(std::sync::atomic::Ordering::Acquire) == 0 { + return; + } + done.await; + } + }) + .await; +} + #[cfg(test)] mod tests { use super::*; + #[tokio::test] + async fn a_background_walk_waits_out_the_foreground_fetch() { + crate::db::with_session(crate::db::Session::empty(), async { + after_foreground().await; + let fg = foreground(); + let second = foreground(); + let waiting = crate::db::spawn_bound(async { + let at = std::time::Instant::now(); + after_foreground().await; + at.elapsed() + }); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + drop(fg); + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + assert!(!waiting.is_finished(), "one foreground fetch still runs"); + drop(second); + let waited = waiting.await.unwrap(); + assert!(waited >= std::time::Duration::from_millis(100) && waited < FOREGROUND_WAIT); + }) + .await; + } + #[tokio::test] async fn a_page_is_claimed_once_until_released() { // A private session: the live one is swapped by tests running alongside. diff --git a/crates/vector-core/src/community/edition.rs b/crates/vector-core/src/community/edition.rs index cbf6a923f..502bfb1b0 100644 --- a/crates/vector-core/src/community/edition.rs +++ b/crates/vector-core/src/community/edition.rs @@ -131,16 +131,122 @@ pub fn build_edition_inner( .finalize_unsigned_with_id(author) } +/// Text an edition carries, shared by every copy of the edition: a held window, the opened-wrap +/// memo and a fold's own list all point at one allocation. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] +pub struct EditionText(std::sync::Arc); + +impl EditionText { + pub fn as_str(&self) -> &str { + &self.0 + } + + /// A subkind, shared from one copy per known value. + pub fn subkind(raw: &str) -> Self { + static KNOWN: std::sync::LazyLock> = + std::sync::LazyLock::new(|| (0..=24).map(|n: u32| EditionText(n.to_string().into())).collect()); + match raw.parse::() { + Ok(n) if is_tag_decimal(raw) && n < KNOWN.len() => KNOWN[n].clone(), + _ => raw.into(), + } + } +} + +impl std::ops::Deref for EditionText { + type Target = str; + fn deref(&self) -> &str { + &self.0 + } +} + +impl AsRef for EditionText { + fn as_ref(&self) -> &str { + &self.0 + } +} + +impl std::borrow::Borrow for EditionText { + fn borrow(&self) -> &str { + &self.0 + } +} + +impl serde::Serialize for EditionText { + fn serialize(&self, s: S) -> Result { + s.serialize_str(&self.0) + } +} + +impl std::fmt::Debug for EditionText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&*self.0, f) + } +} + +impl std::fmt::Display for EditionText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl From for EditionText { + fn from(s: String) -> Self { + EditionText(s.into()) + } +} + +impl From<&str> for EditionText { + fn from(s: &str) -> Self { + EditionText(s.into()) + } +} + +impl From for String { + fn from(t: EditionText) -> String { + t.0.to_string() + } +} + +impl PartialEq for EditionText { + fn eq(&self, o: &str) -> bool { + &*self.0 == o + } +} + +impl PartialEq<&str> for EditionText { + fn eq(&self, o: &&str) -> bool { + &*self.0 == *o + } +} + +impl PartialEq for EditionText { + fn eq(&self, o: &String) -> bool { + *self.0 == **o + } +} + +impl PartialEq for &str { + fn eq(&self, o: &EditionText) -> bool { + *self == &*o.0 + } +} + +impl PartialEq for str { + fn eq(&self, o: &EditionText) -> bool { + self == &*o.0 + } +} + /// A signature-verified, parsed edition. #[derive(Clone, Debug)] pub struct ParsedEdition { /// The real npub that signed (and is thus accountable for) this edition. pub author: PublicKey, - pub vsk: String, + pub vsk: EditionText, pub entity_id: [u8; 32], pub version: u64, pub prev_hash: Option<[u8; 32]>, - pub content: String, + pub content: EditionText, /// [`version::edition_hash`] of this edition — what the next edition's `prev_hash` must cite. pub self_hash: [u8; 32], pub created_at: u64, @@ -204,11 +310,11 @@ pub fn parse_edition_inner(inner: &Event) -> Result Some(h) => Some(decode_hash(&h, "ep")?), None => None, }; - let content = inner.content.clone(); + let content = EditionText::from(inner.content.as_str()); let self_hash = version::edition_hash(&entity_id, version, prev_hash.as_ref(), content.as_bytes()); Ok(ParsedEdition { author: inner.pubkey, - vsk, + vsk: EditionText::subkind(&vsk), entity_id, version, prev_hash, diff --git a/crates/vector-core/src/community/mod.rs b/crates/vector-core/src/community/mod.rs index c31bb3615..ef68b3d6f 100644 --- a/crates/vector-core/src/community/mod.rs +++ b/crates/vector-core/src/community/mod.rs @@ -14,6 +14,7 @@ pub mod raid; pub mod rank; pub mod roles; pub(crate) mod plane_neg; +pub(crate) mod relay_router; pub mod transport; pub mod v2; diff --git a/crates/vector-core/src/community/plane_neg.rs b/crates/vector-core/src/community/plane_neg.rs index 48751aa78..23e765103 100644 --- a/crates/vector-core/src/community/plane_neg.rs +++ b/crates/vector-core/src/community/plane_neg.rs @@ -68,23 +68,50 @@ pub(crate) async fn reconcile(relay: &Relay, filter: Filter, held: &[(EventId, u let (mut negentropy, opening) = open(held).map_err(failed)?; // Listening before the open, so its answer can't slip past. - let mut notifications = relay.notifications(); let sub_id = SubscriptionId::generate(); - // The relay holds the exchange open until told: close it on every way out. - struct CloseGuard(Relay, SubscriptionId); + let mut notifications = super::relay_router::subscribe(relay, &sub_id); + let _reader = crate::boot_probe::Reader::new(); + // The relay holds the exchange open until told. An exchange that ends is closed before this + // returns, so the caller's session slot frees only once the relay has its NEG-CLOSE queued + // ahead of the next NEG-OPEN; one dropped midway is closed from a task. + struct CloseGuard(Option<(Relay, SubscriptionId)>); + impl CloseGuard { + async fn close(mut self) { + if let Some((relay, id)) = self.0.take() { + let _ = relay.send_msg(ClientMessage::NegClose { subscription_id: Cow::Owned(id) }).await; + } + } + } impl Drop for CloseGuard { fn drop(&mut self) { - let (relay, id) = (self.0.clone(), self.1.clone()); + let Some((relay, id)) = self.0.take() else { return }; // spawn-detached: sends a relay NEG-CLOSE, touches no account state. crate::rt::spawn(async move { let _ = relay.send_msg(ClientMessage::NegClose { subscription_id: Cow::Owned(id) }).await; }); } } - let _close = CloseGuard(relay.clone(), sub_id.clone()); + let close = CloseGuard(Some((relay.clone(), sub_id.clone()))); + let ended = exchange(relay, filter, &sub_id, &mut notifications, &mut negentropy, opening, budget, first, idle).await; + close.close().await; + ended +} + +#[allow(clippy::too_many_arguments)] +async fn exchange( + relay: &Relay, + filter: Filter, + sub_id: &SubscriptionId, + notifications: &mut super::relay_router::Route, + negentropy: &mut Negentropy<'_, NegentropyStorageVector>, + opening: Vec, + budget: usize, + first: Duration, + idle: Duration, +) -> Result { relay .send_msg(ClientMessage::NegOpen { - subscription_id: Cow::Borrowed(&sub_id), + subscription_id: Cow::Borrowed(sub_id), filter: Cow::Owned(filter), initial_message: Cow::Owned(crate::simd::hex::bytes_to_hex_string(&opening)), }) @@ -109,7 +136,7 @@ pub(crate) async fn reconcile(relay: &Relay, filter: Filter, held: &[(EventId, u _ => continue, }; match message { - RelayMessage::NegMsg { subscription_id, message } if *subscription_id == sub_id => { + RelayMessage::NegMsg { subscription_id, message } if *subscription_id == *sub_id => { answered = true; let Some(bytes) = crate::simd::hex::hex_string_to_bytes_checked(&message) else { return Err(failed("a reconciliation message that is not hex")); @@ -131,13 +158,13 @@ pub(crate) async fn reconcile(relay: &Relay, filter: Filter, held: &[(EventId, u } Some(next) => { relay - .send_msg(ClientMessage::NegMsg { subscription_id: Cow::Borrowed(&sub_id), message: Cow::Owned(crate::simd::hex::bytes_to_hex_string(&next)) }) + .send_msg(ClientMessage::NegMsg { subscription_id: Cow::Borrowed(sub_id), message: Cow::Owned(crate::simd::hex::bytes_to_hex_string(&next)) }) .await .map_err(|_| Ended::Fail(ReconcileFail::Unreached))?; } } } - RelayMessage::NegErr { subscription_id, message } if *subscription_id == sub_id => { + RelayMessage::NegErr { subscription_id, message } if *subscription_id == *sub_id => { return Err(Ended::Fail(match MachineReadablePrefix::parse(&message) { Some(MachineReadablePrefix::AuthRequired | MachineReadablePrefix::Restricted) => ReconcileFail::Gated, // "blocked:" refuses this exchange, not NIP-77: too many sessions open at once @@ -147,7 +174,7 @@ pub(crate) async fn reconcile(relay: &Relay, filter: Filter, held: &[(EventId, u _ => ReconcileFail::Failed(message.into_owned()), })); } - RelayMessage::Closed { subscription_id, message } if *subscription_id == sub_id => { + RelayMessage::Closed { subscription_id, message } if *subscription_id == *sub_id => { return Err(Ended::Fail(match MachineReadablePrefix::parse(&message) { Some(MachineReadablePrefix::AuthRequired | MachineReadablePrefix::Restricted) => ReconcileFail::Gated, _ => ReconcileFail::Failed(message.into_owned()), diff --git a/crates/vector-core/src/community/policy/normalize.rs b/crates/vector-core/src/community/policy/normalize.rs index ebb753405..57b7125b4 100644 --- a/crates/vector-core/src/community/policy/normalize.rs +++ b/crates/vector-core/src/community/policy/normalize.rs @@ -27,7 +27,7 @@ use super::document::Normalize; use super::types::caps; use std::collections::BTreeSet; -use unicode_normalization::UnicodeNormalization; +use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfc_quick}; /// Shortcodes that render as an image for this community: the bundle's pinned /// Unicode list plus the policy's declared `emoji_codes`. Community-scoped, @@ -61,14 +61,28 @@ fn is_skeleton_alpha(c: char) -> bool { } /// NFC → full case-fold → strip default-ignorables → NFC. +/// +/// ASCII is already NFC, carries no default-ignorable and folds to its lowercase, so it takes +/// one pass; other text skips each NFC pass a quick check proves a no-op. Either way the +/// result is the full definition's, byte for byte. pub fn fold(text: &str) -> String { - let nfc: String = text.nfc().collect(); - let folded: String = nfc - .chars() - .filter(|c| !is_default_ignorable(*c)) - .flat_map(|c| c.to_lowercase()) - .collect(); - folded.nfc().collect() + if text.is_ascii() { + return text.to_ascii_lowercase(); + } + let nfc: std::borrow::Cow = if is_nfc_quick(text.chars()) == IsNormalized::Yes { + std::borrow::Cow::Borrowed(text) + } else { + std::borrow::Cow::Owned(text.nfc().collect()) + }; + let mut folded = String::with_capacity(nfc.len()); + for c in nfc.chars().filter(|c| !is_default_ignorable(*c)) { + folded.extend(c.to_lowercase()); + } + if is_nfc_quick(folded.chars()) == IsNormalized::Yes { + folded + } else { + folded.nfc().collect() + } } /// A `:name:` token: `:` then 1+ of `[A-Za-z0-9_+-]` then `:` (the pinned @@ -89,6 +103,9 @@ fn shortcode_at(s: &str, open: usize) -> Option<(&str, usize)> { /// `skeleton` with community-scoped shortcode resolution. pub fn skeleton(text: &str, codes: &EmojiCodes) -> String { + if text.is_ascii() { + return ascii_skeleton(text, codes); + } // Resolution runs BEFORE folding: the token grammar is ASCII, so ordering // cannot change what resolves, and working on the raw text keeps the name // boundaries intact. @@ -115,6 +132,31 @@ pub fn skeleton(text: &str, codes: &EmojiCodes) -> String { fold(&kept).chars().filter(|c| is_skeleton_alpha(*c)).collect() } +/// [`skeleton`] of ASCII text in one pass: folding ASCII is lowercasing it, and of ASCII only +/// letters are Alphabetic without a Numeric_Type. +fn ascii_skeleton(text: &str, codes: &EmojiCodes) -> String { + let mut out = String::with_capacity(text.len()); + let mut keep = |s: &str| out.extend(s.bytes().filter(u8::is_ascii_alphabetic).map(|b| b.to_ascii_lowercase() as char)); + let bytes = text.as_bytes(); + let (mut i, mut from) = (0usize, 0usize); + while i < bytes.len() { + if bytes[i] == b':' { + if let Some((name, next)) = shortcode_at(text, i) { + keep(&text[from..i]); + if !codes.resolves(name) && name.len() >= caps::MIN_SKELETON_LEN { + keep(name); + } + i = next; + from = next; + continue; + } + } + i += 1; + } + keep(&text[from..]); + out +} + /// Apply a declared normalizer. `Confusables` is declared in the bundle but its /// table is a Phase-2 artifact: it falls back to `fold` and callers mark the /// rule unevaluated rather than approximating a mapping two clients would @@ -189,6 +231,57 @@ mod tests { assert_eq!(skeleton("::", &e), ""); } + /// The bundle's definitions as first written, before the fast paths: what `fold` and + /// `skeleton` must keep returning, byte for byte. + fn fold_reference(text: &str) -> String { + let nfc: String = text.nfc().collect(); + let folded: String = nfc.chars().filter(|c| !is_default_ignorable(*c)).flat_map(|c| c.to_lowercase()).collect(); + folded.nfc().collect() + } + + fn skeleton_reference(text: &str, codes: &EmojiCodes) -> String { + let mut kept = String::with_capacity(text.len()); + let mut i = 0usize; + while i < text.len() { + if text.as_bytes()[i] == b':' { + if let Some((name, next)) = shortcode_at(text, i) { + if !codes.resolves(name) && name.chars().count() >= caps::MIN_SKELETON_LEN { + kept.push_str(name); + } + i = next; + continue; + } + } + let ch = text[i..].chars().next().unwrap(); + kept.push(ch); + i += ch.len_utf8(); + } + fold_reference(&kept).chars().filter(|c| is_skeleton_alpha(*c)).collect() + } + + #[test] + fn fast_paths_match_the_bundle_definitions() { + const PIECES: &[&str] = &[ + "a", "Z", "q", "9", "0", " ", ":", "::", ":fire:", ":vector_logo:", ":buycheapcoinsnow:", ":+1:", "_", "-", + "+", "!", "\n", "é", "e\u{0301}", "ẞ", "ß", "fi", "İ", "Σ", "ς", "\u{200B}", "\u{200D}", "\u{FE0F}", "\u{00AD}", + "👋", "👨\u{200D}👩", "한", "\u{1100}\u{1161}", "Å", "A\u{030A}", "Ⅷ", "٣", "full", "\u{0345}", "ΐ", "Dž", "ff", + ]; + let codes = EmojiCodes::from_policy([&"vector_logo".to_string()]); + let mut seed = 0x2545f4914f6cdd1du64; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..30000 { + let len = (next() % 14) as usize; + let text: String = (0..len).map(|_| PIECES[(next() % PIECES.len() as u64) as usize]).collect(); + assert_eq!(fold(&text), fold_reference(&text), "fold {text:?}"); + assert_eq!(skeleton(&text, &codes), skeleton_reference(&text, &codes), "skeleton {text:?}"); + } + } + #[test] fn confusables_is_declared_but_not_yet_implemented() { assert!(!is_available(Normalize::Confusables)); diff --git a/crates/vector-core/src/community/relay_router.rs b/crates/vector-core/src/community/relay_router.rs new file mode 100644 index 000000000..41d5fae27 --- /dev/null +++ b/crates/vector-core/src/community/relay_router.rs @@ -0,0 +1,180 @@ +//! One listener per relay connection, handing each read only its own subscription's frames. +//! A read that listened to the relay's broadcast itself paid a copy and a wake-up for every frame +//! on the socket, its own or not: eight reads sharing a plane socket read eight times its frames. + +use nostr_sdk::prelude::{Relay, RelayMessage, RelayNotification, SubscriptionId}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::{Arc, LazyLock, Mutex}; +use tokio::sync::mpsc; + +type Tx = mpsc::UnboundedSender; + +#[derive(Default)] +struct Routes { + subs: HashMap, + /// Listeners for the socket's challenges and status only. + watchers: HashMap, +} + +impl Routes { + fn is_empty(&self) -> bool { + self.subs.is_empty() && self.watchers.is_empty() + } +} + +struct Router { + routes: Arc>, + /// Dropped with the router: its task stops listening. + _stop: tokio::sync::oneshot::Sender<()>, +} + +/// By relay connection: its address, held only while the router (and so a read on it) lives. +static ROUTERS: LazyLock>> = LazyLock::new(Default::default); +static NEXT_WATCHER: AtomicU64 = AtomicU64::new(0); +#[cfg(test)] +pub(crate) static STARTED: AtomicU64 = AtomicU64::new(0); + +/// The same relay connection to every clone of its handle, and different for another client's +/// connection to the same URL. +fn connection(relay: &Relay) -> usize { + Arc::as_ptr(relay.capabilities()) as usize +} + +enum Slot { + Sub(SubscriptionId), + Watch(u64), +} + +/// A read's frames from one relay connection: its own subscription's, and what concerns every +/// read on the socket (challenges, notices, status). `None` once the socket's notifications end. +pub(crate) struct Route { + key: usize, + slot: Slot, + rx: mpsc::UnboundedReceiver, +} + +impl Route { + pub(crate) async fn next(&mut self) -> Option { + self.rx.recv().await + } +} + +impl Drop for Route { + fn drop(&mut self) { + let mut routers = ROUTERS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(router) = routers.get(&self.key) else { return }; + let empty = { + let mut routes = router.routes.lock().unwrap_or_else(|e| e.into_inner()); + match &self.slot { + Slot::Sub(id) => routes.subs.remove(id), + Slot::Watch(n) => routes.watchers.remove(n), + }; + routes.is_empty() + }; + if empty { + routers.remove(&self.key); + } + } +} + +/// Frames for subscription `id` on `relay`, listening from now: call before sending its REQ. +pub(crate) fn subscribe(relay: &Relay, id: &SubscriptionId) -> Route { + route(relay, Slot::Sub(id.clone())) +} + +/// The socket's challenges and status, from now. +pub(crate) fn watch(relay: &Relay) -> Route { + route(relay, Slot::Watch(NEXT_WATCHER.fetch_add(1, Relaxed))) +} + +fn route(relay: &Relay, slot: Slot) -> Route { + let key = connection(relay); + let (tx, rx) = mpsc::unbounded_channel(); + let mut routers = ROUTERS.lock().unwrap_or_else(|e| e.into_inner()); + let router = routers.entry(key).or_insert_with(|| start(relay, key)); + let mut routes = router.routes.lock().unwrap_or_else(|e| e.into_inner()); + match &slot { + Slot::Sub(id) => routes.subs.insert(id.clone(), tx), + Slot::Watch(n) => routes.watchers.insert(*n, tx), + }; + drop(routes); + Route { key, slot, rx } +} + +/// The router's task. It holds the socket's notifications, never the relay handle, so it doesn't +/// keep a dropped relay open. +fn start(relay: &Relay, key: usize) -> Router { + use futures_util::StreamExt; + #[cfg(test)] + STARTED.fetch_add(1, Relaxed); + let mut frames = relay.notifications(); + let routes: Arc> = Arc::default(); + let (stop, mut stopped) = tokio::sync::oneshot::channel(); + let ours = routes.clone(); + // spawn-detached: forwards one socket's frames to the reads listening on it; no account state. + crate::rt::spawn(async move { + loop { + let frame = tokio::select! { + f = frames.next() => f, + _ = &mut stopped => return, + }; + let Some(frame) = frame else { break }; + crate::boot_probe::note(&crate::boot_probe::READ_FRAMES); + dispatch(&ours, frame); + } + // The socket's notifications ended: every read on it sees its route end. + let mut routers = ROUTERS.lock().unwrap_or_else(|e| e.into_inner()); + if routers.get(&key).is_some_and(|r| Arc::ptr_eq(&r.routes, &ours)) { + routers.remove(&key); + } + drop(routers); + let mut routes = ours.lock().unwrap_or_else(|e| e.into_inner()); + routes.subs.clear(); + routes.watchers.clear(); + }); + Router { routes, _stop: stop } +} + +fn dispatch(routes: &Mutex, frame: RelayNotification) { + let routes = routes.lock().unwrap_or_else(|e| e.into_inner()); + let own = match &frame { + // A routed read sent its REQ itself, so every event also comes as the relay's message. + RelayNotification::Event { .. } => return, + RelayNotification::Message { message } => match &**message { + RelayMessage::Event { subscription_id, .. } + | RelayMessage::Closed { subscription_id, .. } + | RelayMessage::NegMsg { subscription_id, .. } + | RelayMessage::NegErr { subscription_id, .. } => Some(&**subscription_id), + RelayMessage::EndOfStoredEvents(id) => Some(&**id), + RelayMessage::Auth { .. } => { + for tx in routes.subs.values().chain(routes.watchers.values()) { + let _ = tx.send(frame.clone()); + } + return; + } + RelayMessage::Notice(_) => { + for tx in routes.subs.values() { + let _ = tx.send(frame.clone()); + } + return; + } + _ => return, + }, + RelayNotification::RelayStatus { .. } => { + for tx in routes.subs.values().chain(routes.watchers.values()) { + let _ = tx.send(frame.clone()); + } + return; + } + RelayNotification::Authenticated | RelayNotification::AuthenticationFailed => return, + }; + if let Some(tx) = own.and_then(|id| routes.subs.get(id)) { + let _ = tx.send(frame); + } +} + +#[cfg(test)] +pub(crate) fn routers() -> usize { + ROUTERS.lock().unwrap().len() +} diff --git a/crates/vector-core/src/community/transport.rs b/crates/vector-core/src/community/transport.rs index 058288457..548ae42a4 100644 --- a/crates/vector-core/src/community/transport.rs +++ b/crates/vector-core/src/community/transport.rs @@ -655,16 +655,31 @@ fn next_pooled_id() -> u64 { type PlaneSlots = (u64, std::collections::HashMap); -#[derive(Default)] struct PlanePool { /// The session generation the entries belong to, and the entries by key. slots: std::sync::Mutex, /// Whether a sweep is waiting on the pool's next expiry: one at a time, none for an empty pool. sweep_armed: std::sync::atomic::AtomicBool, + /// How long an unused entry is kept. + ttl: std::time::Duration, +} + +impl Default for PlanePool { + fn default() -> Self { + Self::with_ttl(PLANE_POOL_IDLE_TTL) + } +} + +/// The plane connections held now: how many pooled, how many open, and their clients. +pub fn plane_census() -> (usize, usize, Vec) { + let pooled = PLANE_POOL.lock(); + let open = OPEN_PLANES.lock(); + let clients = pooled.1.values().chain(open.1.values()).map(|p| p.client.clone()).collect(); + (pooled.1.len(), open.1.len(), clients) } static PLANE_POOL: std::sync::LazyLock = std::sync::LazyLock::new(PlanePool::default); -static OPEN_PLANES: std::sync::LazyLock = std::sync::LazyLock::new(PlanePool::default); +static OPEN_PLANES: std::sync::LazyLock = std::sync::LazyLock::new(|| PlanePool::with_ttl(OPEN_PLANE_IDLE_TTL)); /// A pooled connection unused for this long is closed — long enough to span a /// community's whole backfill, short enough not to hoard sockets. @@ -673,19 +688,41 @@ const PLANE_POOL_IDLE_TTL: std::time::Duration = if cfg!(test) { } else { std::time::Duration::from_secs(90) }; -/// Hard cap on simultaneously-pooled plane connections (LRU-evicted). -const PLANE_POOL_MAX: usize = 24; +/// An open connection is one per relay and signed in as nobody, so any later read reuses it: +/// kept for most of a session rather than redialled minutes after a sync. +const OPEN_PLANE_IDLE_TTL: std::time::Duration = if cfg!(test) { + std::time::Duration::from_millis(200) +} else { + std::time::Duration::from_secs(30 * 60) +}; +/// Plane connections dialling at once. +const COLD_PLANES_AT_ONCE: usize = 4; +static COLD_PLANES: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(COLD_PLANES_AT_ONCE); + +/// Frames a plane connection's broadcast holds for a listener that has yet to take them. The +/// buffer is allocated whole, 2,048 frames by default (about 150 KB a connection); one router +/// listens per connection and takes each frame as it lands. +const PLANE_NOTIFICATIONS: usize = 512; + +/// Hard cap on simultaneously-pooled plane connections (LRU-evicted). Room for a large account's +/// whole sync: an evicted plane is dialled and authenticated again a moment later, and idle ones +/// close after [`PLANE_POOL_IDLE_TTL`] anyway. +const PLANE_POOL_MAX: usize = 256; /// Remove the entries idle past the TTL, returning their clients to disconnect. -fn take_expired(pool: &mut std::collections::HashMap, now: web_time::Instant) -> Vec { +fn take_expired(pool: &mut std::collections::HashMap, now: web_time::Instant, ttl: std::time::Duration) -> Vec { let expired: Vec = pool.iter() - .filter(|(_, p)| p.idle() && now.duration_since(p.last_used) >= PLANE_POOL_IDLE_TTL) + .filter(|(_, p)| p.idle() && now.duration_since(p.last_used) >= ttl) .map(|(k, _)| k.clone()) .collect(); expired.into_iter().filter_map(|k| pool.remove(&k)).map(|p| p.client).collect() } impl PlanePool { + fn with_ttl(ttl: std::time::Duration) -> Self { + Self { slots: Default::default(), sweep_armed: Default::default(), ttl } + } + fn lock(&self) -> std::sync::MutexGuard<'_, PlaneSlots> { self.slots.lock().unwrap_or_else(|e| e.into_inner()) } @@ -707,11 +744,11 @@ impl PlanePool { break; } // Only entries in use: look again a TTL on, as releasing one restarts its clock. - let due = next.map_or(PLANE_POOL_IDLE_TTL, |oldest| { - PLANE_POOL_IDLE_TTL.saturating_sub(web_time::Instant::now().duration_since(oldest)) + let due = next.map_or(self.ttl, |oldest| { + self.ttl.saturating_sub(web_time::Instant::now().duration_since(oldest)) }); crate::rt::time::sleep(due).await; - let expired = take_expired(&mut self.lock().1, web_time::Instant::now()); + let expired = take_expired(&mut self.lock().1, web_time::Instant::now(), self.ttl); disconnect_clients(expired); } self.sweep_armed.store(false, std::sync::atomic::Ordering::Release); @@ -726,7 +763,7 @@ impl PlanePool { /// idle TTL expired and resets the whole pool if the session generation advanced /// (a swap). Returns `(Some(client_if_hit), clients_to_disconnect)`. fn take(&self, generation: u64, key: &str) -> (Option, Vec) { - let (hit, evicted) = take_locked(&mut self.lock(), generation, key); + let (hit, evicted) = take_locked(&mut self.lock(), generation, key, self.ttl); (hit.map(|(client, _)| client), evicted) } @@ -737,7 +774,7 @@ impl PlanePool { if generation < g.0 { return None; } - let (_, mut evicted) = take_locked(&mut g, generation, key); + let (_, mut evicted) = take_locked(&mut g, generation, key, self.ttl); if !g.1.contains_key(key) { evicted.extend(make_room(&mut g.1)); g.1.insert(key.to_string(), PooledPlane::new(make())); @@ -802,7 +839,7 @@ impl PlanePool { /// Drops entries idle past the TTL, and every entry if the session generation advanced (a /// swap); a previous session's caller finds nothing and resets nothing. Returns the hit and /// the clients to disconnect. -fn take_locked(g: &mut PlaneSlots, generation: u64, key: &str) -> (Option<(Client, u64)>, Vec) { +fn take_locked(g: &mut PlaneSlots, generation: u64, key: &str, ttl: std::time::Duration) -> (Option<(Client, u64)>, Vec) { if generation < g.0 { return (None, Vec::new()); } @@ -812,7 +849,7 @@ fn take_locked(g: &mut PlaneSlots, generation: u64, key: &str) -> (Option<(Clien g.0 = generation; } let now = web_time::Instant::now(); - evicted.extend(take_expired(&mut g.1, now)); + evicted.extend(take_expired(&mut g.1, now, ttl)); let hit = g.1.get_mut(key).map(|p| { p.last_used = now; (p.client.clone(), p.id) @@ -996,6 +1033,7 @@ fn open_read_permits(key: &str) -> std::sync::Arc { /// relay options, so it routes as they do. fn open_entry(generation: u64, key: &str) -> Option<(Client, InUse)> { let (client, hold, evicted) = OPEN_PLANES.take_or_insert(generation, key, || { + crate::boot_probe::note(&crate::boot_probe::OPEN_DIALS); crate::apply_transport( nostr_sdk::prelude::Client::builder().notification_channel_size(std::num::NonZeroUsize::MIN), crate::transport::Lane::Shared, @@ -1010,7 +1048,7 @@ async fn open_relay(client: &Client, url: &str) -> Option { if let Ok(Some(relay)) = client.relay(url).await { return Some(relay); } - client.add_managed_relay(url).capabilities(crate::community_relay_capabilities()).await.ok()?; + client.add_managed_relay(url).capabilities(crate::community_relay_capabilities()).notification_channel_size(PLANE_NOTIFICATIONS).await.ok()?; client.relay(url).await.ok().flatten() } @@ -1060,7 +1098,7 @@ fn watch_for_challenge(generation: u64, key: &str, relay: &Relay) { if UNWATCHED.lock().unwrap().contains(key) { return; } - let mut notifications = relay.notifications(); + let mut notifications = super::relay_router::watch(relay); let key = key.to_string(); // spawn-detached: one socket's frames into the generation-keyed gate map; no account state. crate::rt::spawn(async move { @@ -1147,7 +1185,11 @@ async fn read_open_plane(generation: u64, url: &str, filter: Filter, timeout: st let key = crate::inbox_relays::normalize_relay_url(url); let Some((client, hold)) = open_plane_client(generation, url, &key, timeout).await else { return OpenRead::Unreachable }; let permits = open_read_permits(&key); + let asked = web_time::Instant::now(); let _permit = permits.acquire().await; + if super::cache::is_foreground() { + crate::boot_probe::FOREGROUND_SLOT_MS.fetch_add(asked.elapsed().as_millis() as u64, std::sync::atomic::Ordering::Relaxed); + } let (gate, events) = match read_relay_eose(&client, url, vec![filter], timeout, true).await { Ok(events) => (settle_gate(generation, &key, hold.id), events), Err(ReadFail::Gated) => (RelayGate::Auth, Vec::new()), @@ -1283,9 +1325,10 @@ async fn read_relay_eose( ) -> Result, ReadFail> { use EoseFail::{Closed, Deadline, Gone}; let relay = client.relay(url).await.map_err(|_| ReadFail::Eose(Gone))?.ok_or(ReadFail::Eose(Gone))?; - // Subscribe to notifications BEFORE the REQ so the EOSE can't slip past. - let mut notifications = relay.notifications(); let sub_id = SubscriptionId::generate(); + // Listening BEFORE the REQ so the EOSE can't slip past. + let mut notifications = super::relay_router::subscribe(&relay, &sub_id); + let _reader = crate::boot_probe::Reader::new(); // Close on every exit — this REQ bypasses the pool's subscription map. // Constructed BEFORE the send: cancellation during the send await must // not leave a queued REQ unguarded (a CLOSE for a never-sent REQ is @@ -1329,12 +1372,14 @@ async fn read_relay_eose( RelayNotification::Event { subscription_id, event } if subscription_id == sub_id && seen.insert(event.id) => { + crate::boot_probe::note(&crate::boot_probe::READ_KEPT); events.push(*event); } RelayNotification::Message { message } => match *message { RelayMessage::Event { subscription_id, event } if *subscription_id == sub_id && seen.insert(event.id) => { + crate::boot_probe::note(&crate::boot_probe::READ_KEPT); events.push(event.into_owned()); } RelayMessage::EndOfStoredEvents(id) if *id == sub_id => return Ok(events), @@ -1607,6 +1652,15 @@ impl LiveTransport { // the win: the NIP-42 handshake happens ONCE, not per page/epoch. let (hit, evicted) = PLANE_POOL.take(generation, &key); disconnect_clients(evicted); + if let Some(c) = hit { + return c; + } + // Each cold plane dials every community relay and authenticates on each: unbounded, + // a cold boot opens dozens at once. Background sync dials a few at a time, the reader's + // own fetch without waiting, and a plane another read built meanwhile is reused. + let _permit = if super::cache::is_foreground() { None } else { COLD_PLANES.acquire().await.ok() }; + let (hit, evicted) = PLANE_POOL.take(generation, &key); + disconnect_clients(evicted); if let Some(c) = hit { c } else { @@ -1616,6 +1670,7 @@ impl LiveTransport { // Authenticates as the PLANE key, not the user — hence its own // authenticator rather than `nostr_client_builder()`, which resolves the // session identity. + crate::boot_probe::note_plane(&key); let auth = nostr_sdk::prelude::SignerAuthenticator::new(plane.clone()); #[cfg(test)] let auth = tests::SlowAuth(auth); @@ -1633,7 +1688,7 @@ impl LiveTransport { // plane fetch — and the NIP-42 auth AS the plane key — would connect // direct and tie the user's IP to community membership. for r in targets { - let _ = client.add_managed_relay(r.clone()).capabilities(crate::community_relay_capabilities()).await; + let _ = client.add_managed_relay(r.clone()).capabilities(crate::community_relay_capabilities()).notification_channel_size(PLANE_NOTIFICATIONS).await; } let mut frames = Vec::with_capacity(targets.len()); for r in targets { @@ -1663,6 +1718,9 @@ impl LiveTransport { // own, and a relay may answer a REQ that reaches it before the AUTH with nothing. let budget = crate::relay_request_timeout(std::time::Duration::from_secs(5)); futures_util::future::join_all(frames.into_iter().map(|f| authenticated(f, budget))).await; + if super::cache::is_foreground() { + crate::boot_probe::FOREGROUND_DIAL_MS.fetch_add(opened.elapsed().as_millis() as u64, std::sync::atomic::Ordering::Relaxed); + } let ev = PLANE_POOL.insert(generation, key, client.clone()); disconnect_clients(ev); crate::log_debug!("[v2:plane] a connection as {} to {} relay(s) opened in {:?}", &plane.public_key().to_hex()[..8], targets.len(), opened.elapsed()); @@ -1725,6 +1783,7 @@ impl LiveTransport { /// reads the counts to decide whether its cursor may advance (full coverage /// only — a majority return must not skip a down relay's pending editions). pub async fn fetch_counted(&self, query: &Query, relays: &[String]) -> Result<(Vec, usize, usize), String> { + crate::boot_probe::note(&crate::boot_probe::FETCHES); let client = Self::warm_client(relays, self.timeout).await?; let base_timeout = self.timeout; let filter = query.to_filter(); @@ -3059,6 +3118,82 @@ mod tests { // ── Plane connections by relay gate ─────────────────────────────────────── + /// Not a check: what concurrent reads on one connection cost, against the same reads in turn. + /// `cargo nextest run -p vector-core read_fanout --run-ignored only --no-capture` + #[cfg(unix)] + #[tokio::test(flavor = "multi_thread", worker_threads = 8)] + #[ignore] + async fn read_fanout() { + use nostr_sdk::prelude::FinalizeEvent; + let relay = wire::WireRelay::start().await; + let reads: usize = std::env::var("READ_FANOUT_READS").ok().and_then(|n| n.parse().ok()).unwrap_or(8); + let authors: Vec = (0..reads).map(|_| Keys::generate()).collect(); + let body = "x".repeat(1500); + for a in &authors { + relay.hold((0..4800 / reads).map(|i| EventBuilder::new(Kind::Custom(1059), format!("{i}{body}")).finalize(a).unwrap())); + } + let client = nostr_sdk::prelude::Client::builder().build(); + crate::ClientRelayExt::add_managed_relay(&client, relay.url()).await.unwrap(); + client.connect().await; + client.relay(relay.url()).await.unwrap().unwrap().wait_for_connection(std::time::Duration::from_secs(5)).await; + let read = |a: &Keys| { + let (client, url, f) = (client.clone(), relay.url(), Filter::new().author(a.public_key())); + async move { fetch_relay_eose_filters(&client, &url, vec![f], std::time::Duration::from_secs(60)).await.unwrap().len() } + }; + fn usage() -> (f64, i64, i64) { + let mut u: libc::rusage = unsafe { std::mem::zeroed() }; + unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut u) }; + let t = |v: libc::timeval| v.tv_sec as f64 + v.tv_usec as f64 / 1e6; + (t(u.ru_utime) + t(u.ru_stime), u.ru_minflt as i64, (u.ru_nvcsw + u.ru_nivcsw) as i64) + } + for round in 0..2 { + let (c0, f0, s0) = usage(); + let r0 = crate::boot_probe::READ_FRAMES.load(std::sync::atomic::Ordering::Relaxed); + let started = std::time::Instant::now(); + let n: usize = futures_util::future::join_all(authors.iter().map(read)).await.iter().sum(); + let (c1, f1, s1) = usage(); + let r1 = crate::boot_probe::READ_FRAMES.load(std::sync::atomic::Ordering::Relaxed); + println!("round {round} together: {n} events in {:?}, cpu {:.2}s faults {} switches {} frames read {}", started.elapsed(), c1 - c0, f1 - f0, s1 - s0, r1 - r0); + let started = std::time::Instant::now(); + let mut n = 0; + for a in &authors { + n += read(a).await; + } + let (c2, f2, s2) = usage(); + let r2 = crate::boot_probe::READ_FRAMES.load(std::sync::atomic::Ordering::Relaxed); + println!("round {round} in turn: {n} events in {:?}, cpu {:.2}s faults {} switches {} frames read {}", started.elapsed(), c2 - c1, f2 - f1, s2 - s1, r2 - r1); + } + } + + /// Many reads at once on one connection, with a plane connection's broadcast, each get all of + /// their own events and their EOSE: when + /// every read listened to the socket's whole broadcast, its backlog overran and reads waited + /// out their deadline for an EOSE that had been dropped. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + async fn many_reads_on_one_socket_each_get_their_own() { + use nostr_sdk::prelude::FinalizeEvent; + let relay = wire::WireRelay::start().await; + let authors: Vec = (0..32).map(|_| Keys::generate()).collect(); + for a in &authors { + relay.hold((0..300).map(|i| EventBuilder::new(Kind::Custom(1059), format!("{i}{}", "x".repeat(500))).finalize(a).unwrap())); + } + let client = nostr_sdk::prelude::Client::builder().build(); + crate::ClientRelayExt::add_managed_relay(&client, relay.url()).notification_channel_size(PLANE_NOTIFICATIONS).await.unwrap(); + client.connect().await; + client.relay(relay.url()).await.unwrap().unwrap().wait_for_connection(std::time::Duration::from_secs(5)).await; + let reads = authors.iter().map(|a| { + let (client, url, f) = (client.clone(), relay.url(), Filter::new().author(a.public_key())); + let me = a.public_key(); + async move { + let got = fetch_relay_eose_filters(&client, &url, vec![f], std::time::Duration::from_secs(10)).await.ok()?; + got.iter().all(|e| e.pubkey == me).then_some(got.len()) + } + }); + let got = futures_util::future::join_all(reads).await; + assert!(got.iter().all(|n| *n == Some(300)), "{got:?}"); + assert_eq!(super::super::relay_router::routers(), 0, "the last read out stops its socket's router"); + } + /// A plane key and the one wrap it authored, held by `relay`. fn plane_on(relay: &wire::WireRelay) -> (Keys, Event) { use nostr_sdk::prelude::FinalizeEvent; diff --git a/crates/vector-core/src/community/v2/chat.rs b/crates/vector-core/src/community/v2/chat.rs index 79cba6b5e..fccadf3e0 100644 --- a/crates/vector-core/src/community/v2/chat.rs +++ b/crates/vector-core/src/community/v2/chat.rs @@ -229,6 +229,34 @@ pub fn build_reaction_rumor( stream::build_rumor_ms(kind::REACTION, author, emoji_content, tags, at_ms) } +/// Build a kind-1068 poll rumor (NIP-88): the question is its content, `extra_tags` carries the +/// poll's description ([`crate::polls::Poll::wire_tags`]) and anything a message would. +pub fn build_poll_rumor(author: PublicKey, channel_id: &ChannelId, epoch: Epoch, question: &str, extra_tags: Vec, at_ms: u64) -> UnsignedEvent { + let mut tags = stream::channel_binding_tags(channel_id, epoch); + tags.extend(extra_tags); + stream::build_rumor_ms(kind::POLL, author, question, tags, at_ms) +} + +/// Build a kind-1018 vote rumor (NIP-88) on the poll `poll_id_hex`. `expiration` is the poll's, +/// so a vote never outlives what it answers. +pub fn build_poll_vote_rumor( + author: PublicKey, + channel_id: &ChannelId, + epoch: Epoch, + poll_id_hex: &str, + responses: Vec>, + expiration: Option, + at_ms: u64, +) -> UnsignedEvent { + let mut tags = stream::channel_binding_tags(channel_id, epoch); + tags.push(Tag::custom("e", [poll_id_hex.to_string()])); + tags.extend(responses.into_iter().filter_map(|t| Tag::parse(t).ok())); + if let Some(at) = expiration { + tags.push(Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at))); + } + stream::build_rumor_ms(kind::POLL_VOTE, author, "", tags, at_ms) +} + /// Build a kind-5 delete rumor (NIP-09): `e` = the target rumor id, `k` = its /// kind. Semantic within the plane only — members stop rendering; the wrap /// ciphertext on relays needs a separate NIP-09 scrub by its `p` tag. @@ -502,6 +530,9 @@ pub enum ChatEvent { new_content: String, emoji: Vec<(String, String)>, }, + /// Kind 1018 — a NIP-88 vote on the poll `target`. Its `response` tags are read against + /// the poll when it folds, since only the poll declares which ids count. + PollVote { opened: OpenedStream, target: [u8; 32] }, /// Kind 3310 — payload opaque, read `opened.rumor` directly. Webxdc { opened: OpenedStream }, /// Kind 23311 — the event's presence is the whole signal. @@ -529,6 +560,7 @@ impl ChatEvent { | ChatEvent::Reaction { opened, .. } | ChatEvent::Delete { opened, .. } | ChatEvent::Edit { opened, .. } + | ChatEvent::PollVote { opened, .. } | ChatEvent::Webxdc { opened } | ChatEvent::Typing { opened } | ChatEvent::VoicePresence { opened, .. } @@ -645,7 +677,7 @@ pub fn scoped_cert_of(rumor: &UnsignedEvent) -> Option<([u8; 64], u64)> { pub fn writer_bit(kind: u16) -> Option { use crate::community::roles::Permissions; match kind { - kind::REACTION => Some(Permissions::ADD_REACTIONS), + kind::REACTION | kind::POLL_VOTE => Some(Permissions::ADD_REACTIONS), kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE => Some(Permissions::CONNECT), kind::DELETE => None, _ => Some(Permissions::SEND_MESSAGES), @@ -690,7 +722,7 @@ pub fn with_writer_cert(rumor: UnsignedEvent, wepoch: Epoch, cert: Option bool { - locked || !matches!(kind, kind::REACTION | kind::DELETE | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE) + locked || !matches!(kind, kind::REACTION | kind::POLL_VOTE | kind::DELETE | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE) } /// Open a chat wrap against every `(epoch, secret)` a client holds for one @@ -723,7 +755,7 @@ pub fn open_chat_event_multi( fn is_chat_kind(k: u16) -> bool { matches!( k, - kind::MESSAGE | kind::COMMENT | kind::REACTION | kind::DELETE | kind::EDIT | kind::WEBXDC | kind::TYPING | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE + kind::MESSAGE | kind::COMMENT | kind::POLL | kind::POLL_VOTE | kind::REACTION | kind::DELETE | kind::EDIT | kind::WEBXDC | kind::TYPING | kind::VOICE_PRESENCE | kind::VOICE_DIRECTIVE ) } @@ -749,6 +781,14 @@ fn parse_chat_rumor(opened: OpenedStream) -> Result { let emoji = collect_emoji(&opened.rumor); Ok(ChatEvent::Message { opened, reply_to, emoji }) } + kind::POLL => { + let emoji = collect_emoji(&opened.rumor); + Ok(ChatEvent::Message { opened, reply_to: None, emoji }) + } + kind::POLL_VOTE => { + let target = decode_id32(required_tag(&opened.rumor, TAG_TARGET)?, TAG_TARGET)?; + Ok(ChatEvent::PollVote { opened, target }) + } kind::COMMENT => { // A threaded reply (NIP-22, CORD-03 §3). Vector's timeline renders it // INLINE: the immediate parent (the lowercase `e`) becomes the reply @@ -1511,4 +1551,14 @@ mod tests { Err(ChatError::MissingTag(TAG_TARGET_AUTHOR)) )); } + + #[test] + fn a_vote_rides_like_a_reaction_but_a_poll_like_a_post() { + use crate::community::roles::Permissions; + assert_eq!(writer_bit(kind::POLL_VOTE), Some(Permissions::ADD_REACTIONS)); + assert_eq!(writer_bit(kind::POLL), Some(Permissions::SEND_MESSAGES)); + assert!(!rides_writer_address(kind::POLL_VOTE, false), "a restricted Channel's members still vote"); + assert!(rides_writer_address(kind::POLL_VOTE, true), "a locked one takes votes only from writers"); + assert!(rides_writer_address(kind::POLL, false)); + } } diff --git a/crates/vector-core/src/community/v2/control.rs b/crates/vector-core/src/community/v2/control.rs index bc7c574cc..2911c3502 100644 --- a/crates/vector-core/src/community/v2/control.rs +++ b/crates/vector-core/src/community/v2/control.rs @@ -221,11 +221,11 @@ pub fn parse_edition_rumor(rumor: &UnsignedEvent) -> Result Result<(ParsedEdition, OpenedStream), ControlError> { - let opened = self.opened(wrap)?; - Ok((opened.0.clone(), opened.1.clone())) + // The stream (rumor and seal) is for a re-wrap, which is rare: it is opened again rather than held. + let opened = stream::open_wrap_at(wrap, &self.pk, &self.conv_key, self.restricted)?; + if opened.seal_form != SealForm::Plaintext { + return Err(ControlError::NotPlaintextSealed); + } + let edition = parse_edition_rumor(&opened.rumor)?; + self.bound(&edition)?; + Ok((edition, opened)) } /// [`Self::open`] for a reader that needs only the edition. pub fn open_edition(&self, wrap: &Event) -> Result { - Ok(self.opened(wrap)?.0.clone()) + Ok((*self.opened(wrap)?).clone()) } fn opened(&self, wrap: &Event) -> Result { @@ -383,25 +389,31 @@ impl ControlPlane { return Err(ControlError::NotPlaintextSealed); } let edition = parse_edition_rumor(&opened.rumor)?; - let bytes = wrap.content.len() * 2 + edition.content.len() + 512; - let opened = std::sync::Arc::new((edition, opened)); - memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, opened.clone(), bytes); - opened + let bytes = std::mem::size_of::() + edition.content.len() + 64; + let edition = std::sync::Arc::new(edition); + memo.lock().unwrap_or_else(|e| e.into_inner()).insert(memo_key, edition.clone(), bytes); + edition } }; - // A marked edition from another Community, re-wrapped here, is not this Community's. - if opened.0.binding.is_some_and(|b| self.binding.is_some_and(|mine| mine != b)) { + self.bound(&opened)?; + Ok(opened) + } + + /// A marked edition from another Community, re-wrapped here, is not this Community's. + fn bound(&self, edition: &ParsedEdition) -> Result<(), ControlError> { + if edition.binding.is_some_and(|b| self.binding.is_some_and(|mine| mine != b)) { return Err(ControlError::Edition(EditionError::BadField("eb"))); } - Ok(opened) + Ok(()) } } /// Bytes per generation of the session's [`OpenedMemo`]: a follow re-reads every edition the -/// plane serves, and a large plane runs to a few thousand of them. -const OPENED_MEMO_BYTES: usize = 8 << 20; +/// plane serves, and a large plane runs to a few thousand of them. Counted as held: the edition +/// and its text, which every copy of the edition shares. +const OPENED_MEMO_BYTES: usize = 2 << 20; -type Opened = std::sync::Arc<(ParsedEdition, OpenedStream)>; +type Opened = std::sync::Arc; /// Control wraps already opened, in two generations: a full `cur` ages into `prev`, and a hit /// in `prev` moves back, so a working set within the bound never goes cold all at once. @@ -877,10 +889,6 @@ pub async fn genesis_signed( #[cfg(test)] mod tests { - fn shown(r: Result<(ParsedEdition, OpenedStream), ControlError>) -> String { - format!("{r:?}") - } - #[test] fn an_open_served_from_the_memo_is_exactly_a_fresh_open() { let owner = Keys::generate(); @@ -890,11 +898,11 @@ mod tests { assert!(!g.wraps.is_empty()); for wrap in &g.wraps { forget_opened(); - let fresh = shown(view.open(wrap)); + let fresh = format!("{:?}", view.open(wrap).map(|(e, _)| e)); assert!(fresh.starts_with("Ok"), "{fresh}"); + assert_eq!(format!("{:?}", view.open_edition(wrap)), fresh, "the memo's first open is a fresh open"); assert!(opened_held(&view, wrap), "the open is kept"); - assert_eq!(shown(view.open(wrap)), fresh, "and served again as it was"); - assert_eq!(format!("{:?}", view.open_edition(wrap)), format!("{:?}", view.open(wrap).map(|(e, _)| e))); + assert_eq!(format!("{:?}", view.open_edition(wrap)), fresh, "and served again as it was"); } } @@ -906,8 +914,8 @@ mod tests { let a = super::super::community::CommunityV2::from_genesis(&g, "A", None, vec![], 0); let b = super::super::community::CommunityV2::from_genesis(&other, "B", None, vec![], 0); forget_opened(); - assert!(ControlPlane::of(&a).open(&g.wraps[0]).is_ok()); - assert!(ControlPlane::of(&b).open(&g.wraps[0]).is_err(), "another Community's view opens nothing of A's"); + assert!(ControlPlane::of(&a).open_edition(&g.wraps[0]).is_ok()); + assert!(ControlPlane::of(&b).open_edition(&g.wraps[0]).is_err(), "another Community's view opens nothing of A's"); // A bare group view checks no binding; this Community's view still does, cached or not. let mut legacy = a.clone(); @@ -916,10 +924,11 @@ mod tests { let elsewhere = super::super::derive::edition_binding(&CommunityId([0x42; 32])); let rumor = build_edition_rumor_bound(owner.public_key(), vsk::ROLE_V2, &[0x51; 32], 1, None, "{}", 1_000, None, Some(elsewhere)); let (wrap, _) = seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap(); - assert!(ControlPlane::legacy(&group).open(&wrap).is_ok()); + assert!(ControlPlane::legacy(&group).open_edition(&wrap).is_ok()); assert!(opened_held(&ControlPlane::of(&legacy), &wrap), "the same address and key: one memo entry"); + assert!(matches!(ControlPlane::of(&legacy).open(&wrap), Err(ControlError::Edition(EditionError::BadField("eb"))))); assert!( - matches!(ControlPlane::of(&legacy).open(&wrap), Err(ControlError::Edition(EditionError::BadField("eb")))), + matches!(ControlPlane::of(&legacy).open_edition(&wrap), Err(ControlError::Edition(EditionError::BadField("eb")))), "an edition bound to another Community is refused whoever filled the memo" ); } @@ -929,7 +938,7 @@ mod tests { let owner = Keys::generate(); let g = genesis(&owner, CommunityMetadata { name: "Ages".into(), ..Default::default() }, 1_000).unwrap(); let held = super::super::community::CommunityV2::from_genesis(&g, "Ages", None, vec![], 0); - let value: Opened = std::sync::Arc::new(ControlPlane::of(&held).open(&g.wraps[0]).unwrap()); + let value: Opened = std::sync::Arc::new(ControlPlane::of(&held).open_edition(&g.wraps[0]).unwrap()); let half = OPENED_MEMO_BYTES / 2 + 1; let mut memo = OpenedMemo::default(); memo.insert([1; 32], value.clone(), half); diff --git a/crates/vector-core/src/community/v2/inbound.rs b/crates/vector-core/src/community/v2/inbound.rs index 9a3ebebef..212c9b8bd 100644 --- a/crates/vector-core/src/community/v2/inbound.rs +++ b/crates/vector-core/src/community/v2/inbound.rs @@ -68,6 +68,10 @@ pub fn chat_message_to_message( wrapper_event_id: Some(opened.wrapper_id.to_hex()), // Self-Destruct Timer: the sender's NIP-40 expiry drives our local purge. expiration: chat::message_expiration(&opened.rumor), + poll: (opened.rumor.kind.as_u16() == super::kind::POLL) + .then(|| crate::polls::Poll::from_tags(opened.rumor.tags.iter().map(|t| t.as_slice()))) + .flatten() + .map(Box::new), ..Default::default() } } @@ -401,6 +405,40 @@ fn apply_chat_to_state_in( let _ = state.remove_message(&target_id); Some(ChatPersist::Removed { id: target_id, moderated: author != opened.author }) } + ChatEvent::PollVote { opened, target } => { + let target_id = crate::simd::hex::bytes_to_hex_32(target); + let voter = opened.author.to_bech32().ok()?; + // Same-channel only, as for reactions: the vote's binding names its own channel. + let (chat, poll) = state.find_message(&target_id)?; + if chat.id != channel_id { + return None; + } + let picks = poll.poll.as_ref()?.picks_from_tags(opened.rumor.tags.iter().map(|t| t.as_slice())); + let vote = crate::polls::PollVote { id: opened.rumor_id.to_hex(), voter: voter.clone(), picks, at: opened.at_ms }; + let mut added = false; + let (_c, message) = state.update_message_with(&target_id, |m, i| added = m.add_poll_vote(vote, i))?; + if !added { + return None; + } + let vote_event = crate::stored_event::StoredEventBuilder::new() + .id(opened.rumor_id.to_hex()) + .kind(super::kind::POLL_VOTE) + .content(String::new()) + .tags( + std::iter::once(vec!["e".to_string(), target_id.clone()]) + .chain(message.poll.as_ref().map(|p| p.response_tags(picks)).unwrap_or_default()) + .chain((opened.at_ms % 1000 > 0).then(|| vec!["ms".to_string(), (opened.at_ms % 1000).to_string()])) + .chain(chat::message_expiration(&opened.rumor).map(|e| vec!["expiration".to_string(), e.to_string()])) + .collect(), + ) + .reference_id(Some(target_id)) + .wrapper_event_id(Some(opened.wrapper_id.to_hex())) + .created_at(opened.at_ms / 1000) + .mine(opened.author == *my_pubkey) + .npub(Some(voter)) + .build(); + Some(ChatPersist::Updated { message, edit_event: Some(Box::new(vote_event)) }) + } ChatEvent::Typing { .. } | ChatEvent::Webxdc { .. } | ChatEvent::VoicePresence { .. } | ChatEvent::VoiceDirective { .. } => None, } } @@ -409,7 +447,7 @@ fn apply_chat_to_state_in( /// it isn't resident: STATE holds a window, and the aggregate must land on older rows too. pub async fn hydrate_target(event: &ChatEvent, channel_id: &str) { let msg_id = match event { - ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } => crate::simd::hex::bytes_to_hex_32(target), + ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } | ChatEvent::PollVote { target, .. } => crate::simd::hex::bytes_to_hex_32(target), ChatEvent::Delete { target, .. } => { let id = crate::simd::hex::bytes_to_hex_32(target); if crate::state::STATE.lock().await.find_reaction(&id).is_some() { @@ -437,7 +475,7 @@ pub async fn hydrate_target(event: &ChatEvent, channel_id: &str) { /// whose hydration has already loaded any stored target. pub async fn awaits_target(event: &ChatEvent) -> bool { let target = match event { - ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } | ChatEvent::Delete { target, .. } => { + ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } | ChatEvent::PollVote { target, .. } | ChatEvent::Delete { target, .. } => { crate::simd::hex::bytes_to_hex_32(target) } _ => return false, @@ -556,7 +594,7 @@ pub async fn notify_chat_outcome(handler: &dyn InboundEventHandler, channel_id: handler.on_community_update(channel_id, &message.id, &message); match (edit_event, event) { _ if !news() => {} - (Some(_), _) => handler.on_message_edited(channel_id, &message, at), + (Some(_), ChatEvent::Edit { .. }) => handler.on_message_edited(channel_id, &message, at), (None, ChatEvent::Reaction { opened, .. }) => { let id = opened.rumor_id.to_hex(); if let Some(reaction) = message.reactions.iter().find(|r| r.id == id) { diff --git a/crates/vector-core/src/community/v2/mod.rs b/crates/vector-core/src/community/v2/mod.rs index 64b470568..ef9942f5d 100644 --- a/crates/vector-core/src/community/v2/mod.rs +++ b/crates/vector-core/src/community/v2/mod.rs @@ -50,6 +50,10 @@ pub mod kind { pub const REACTION: u16 = 7; /// Delete (NIP-09 shape: `e` names the author's own rumor id). pub const DELETE: u16 = 5; + /// NIP-88 poll: content = the question, `option` tags the choices. + pub const POLL: u16 = crate::polls::KIND_POLL; + /// NIP-88 vote: `e` = the poll's rumor id, one `response` per chosen option. + pub const POLL_VOTE: u16 = crate::polls::KIND_POLL_VOTE; /// Message edit (fields unpinned upstream; Vector: `e` = own message rumor id, /// content = replacement text). pub const EDIT: u16 = 3302; diff --git a/crates/vector-core/src/community/v2/realtime.rs b/crates/vector-core/src/community/v2/realtime.rs index 5253e7cfd..efe98ea83 100644 --- a/crates/vector-core/src/community/v2/realtime.rs +++ b/crates/vector-core/src/community/v2/realtime.rs @@ -483,6 +483,7 @@ fn reread_moved_channels(before: &CommunityV2) { if !crate::db::current_session().is_live() { return; } + crate::community::cache::after_foreground().await; crate::VectorCore::v2_backfill_channel(&id, &channel, 50, 8, None, None, crate::community::transport::Evidence::Fast, 12).await; } }); @@ -1908,6 +1909,7 @@ async fn adopt_parked_keys( // A few rooms at a time: a Role that opens several fills them together. let rooms: Vec = rooms.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.0)).collect(); for rooms in rooms.chunks(KEYED_BACKFILL_CONCURRENCY) { + crate::community::cache::after_foreground().await; let fills = futures_util::future::join_all(rooms.iter().map(|hex| { crate::VectorCore::v2_backfill_channel(id, hex, 50, 2, None, None, crate::community::transport::Evidence::Fast, 12) })) diff --git a/crates/vector-core/src/community/v2/service.rs b/crates/vector-core/src/community/v2/service.rs index b370ebe14..42f67870b 100644 --- a/crates/vector-core/src/community/v2/service.rs +++ b/crates/vector-core/src/community/v2/service.rs @@ -282,8 +282,14 @@ pub async fn try_send_chat_message_at( at_ms: u64, ) -> Result { let (author_pk, group, epoch) = chat_send_context(community, channel_id)?; - refuse_while_timed_out(community, &author_pk)?; - // An honest client posts only where it holds Send Messages (CORD-04 §8). + refuse_unless_posting(community, channel_id, &author_pk)?; + let rumor = chat::build_message_rumor(author_pk, channel_id, epoch, content, reply_to, emoji, extra_tags, at_ms); + publish_chat_tracked(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await +} + +/// An honest client posts only where it holds Send Messages (CORD-04 §8), and not while timed out. +fn refuse_unless_posting(community: &CommunityV2, channel_id: &ChannelId, author_pk: &PublicKey) -> Result<(), String> { + refuse_while_timed_out(community, author_pk)?; let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default(); let owner = community.owner().ok().map(|o| o.to_hex()); if roster.everyone.is_some() @@ -293,10 +299,61 @@ pub async fn try_send_chat_message_at( { return Err("you can't send messages in this channel".into()); } - let rumor = chat::build_message_rumor(author_pk, channel_id, epoch, content, reply_to, emoji, extra_tags, at_ms); + Ok(()) +} + +/// Post a NIP-88 poll (kind 1068) at `at_ms`: `question` is its content, `extra_tags` its +/// description plus anything a message carries (an expiry). Returns the poll's rumor id. +pub async fn try_send_poll_at( + transport: &T, + community: &CommunityV2, + channel_id: &ChannelId, + question: &str, + extra_tags: Vec, + at_ms: u64, +) -> Result { + let (author_pk, group, epoch) = chat_send_context(community, channel_id)?; + refuse_unless_posting(community, channel_id, &author_pk)?; + let rumor = chat::build_poll_rumor(author_pk, channel_id, epoch, question, extra_tags, at_ms); publish_chat_tracked(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await } +/// Vote on a poll (kind 1018). A vote rides like a reaction: anyone who may react votes, except +/// in a locked Channel, whose writer address only writers reach. One vote each: a member who +/// already voted is refused. `picks` is a bitmask over the poll's options. +pub async fn send_poll_vote( + transport: &T, + community: &CommunityV2, + channel_id: &ChannelId, + poll_id_hex: &str, + picks: u32, +) -> Result { + let (author_pk, group, epoch) = chat_send_context(community, channel_id)?; + refuse_while_timed_out(community, &author_pk)?; + refuse_unless_reacting(community, channel_id, &author_pk).map_err(|_| "you can't vote in this channel".to_string())?; + let resident = crate::state::STATE.lock().await.find_message(poll_id_hex).map(|(_, m)| m); + let message = match resident { + Some(m) => m, + None => crate::db::events::get_message_by_id(poll_id_hex).await.ok().flatten().map(|(_, m)| m).ok_or("that poll isn't here")?, + }; + let poll = message.poll.as_deref().ok_or("that poll isn't here")?; + let me = nostr_sdk::prelude::ToBech32::to_bech32(&author_pk).map_err(|e| e.to_string())?; + if poll.has_voted(&me) { + return Err("you've already voted in this poll".into()); + } + if poll.ended(crate::clock::now_secs()) { + return Err("this poll has ended".into()); + } + let picks = if poll.multi { picks } else { picks & picks.wrapping_neg() }; + let responses = poll.response_tags(picks); + if responses.is_empty() { + return Err("pick an option first".into()); + } + let at_ms = next_send_ms(); + let rumor = chat::build_poll_vote_rumor(author_pk, channel_id, epoch, poll_id_hex, responses, message.expiration, at_ms); + publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await +} + /// A member timed out doesn't post, edit or react until it ends (CORD-04 §8). fn refuse_while_timed_out(community: &CommunityV2, author: &PublicKey) -> Result<(), String> { match community_timeouts(community)?.get(author) { @@ -713,7 +770,7 @@ async fn publish_chat_tracked( } // Reactions are left out: one that lands long after the user moved on surprises. let kept = !ephemeral - && matches!(rumor.kind.as_u16(), super::kind::MESSAGE | super::kind::COMMENT | super::kind::EDIT | super::kind::DELETE); + && matches!(rumor.kind.as_u16(), super::kind::MESSAGE | super::kind::COMMENT | super::kind::POLL | super::kind::EDIT | super::kind::DELETE); if kept { outbox::keep(&rumor_id, &wrap); } @@ -1134,41 +1191,52 @@ pub async fn fetch_channel_history_since_epoch( let mut read_full = false; let lowest_since = if whole.is_empty() { read_since } else { read_since.min(whole_since) }; let read_planes_here: &[(ReadPlane, Epoch)] = if read_on && !lowest_since.zip(read_until).is_some_and(|(s, u)| s > u) { &planes } else { &[] }; - for (plane, _) in read_planes_here { + // Every address's page at once: each is its own read, and in series they were most + // of a channel's first paint. + let plane_reads = futures_util::future::join_all(read_planes_here.iter().map(|(plane, _)| { let since = if whole.contains(&plane.address()) { whole_since } else { read_since }; let q = Query { since, evidence, ..plane_page(plane.address().to_hex(), page, read_until) }; - // A read view holds no key to authenticate as the plane, so it asks plainly. - let fetched = match plane.group() { - Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| { - complete &= f.is_complete(); - f.events - }), - None => transport.fetch(&q, &community.relays).await, + async move { + // A read view holds no key to authenticate as the plane, so it asks plainly. + match plane.group() { + Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| (f.is_complete(), f.events)), + None => transport.fetch(&q, &community.relays).await.map(|evs| (true, evs)), + } + } + })); + let writer_reads = futures_util::future::join_all(writer_planes.iter().map(|(address, wepoch)| { + let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) }; + let live_writer = &live_writer; + async move { + // Only a writer can authenticate as the address. + match live_writer { + Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| (f.is_complete(), f.events)), + _ => transport.fetch(&q, &community.relays).await.map(|evs| (true, evs)), + } + } + })); + let (plane_reads, writer_reads) = futures_util::future::join(plane_reads, writer_reads).await; + for fetched in plane_reads { + let Ok((whole_read, evs)) = fetched else { + complete = false; + continue; }; - complete &= fetched.is_ok(); - if let Ok(evs) = fetched { - answered = true; - read_full |= evs.len() >= page; - note_page(&evs); - for e in evs { - if wrap_ids.insert(e.id) { - wraps.push(e); - } + complete &= whole_read; + answered = true; + read_full |= evs.len() >= page; + note_page(&evs); + for e in evs { + if wrap_ids.insert(e.id) { + wraps.push(e); } } } - for (address, wepoch) in &writer_planes { - let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) }; - // Only a writer can authenticate as the address. - let fetched = match &live_writer { - Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| { - complete &= f.is_complete(); - f.events - }), - _ => transport.fetch(&q, &community.relays).await, + for fetched in writer_reads { + let Ok((whole_read, fetched)) = fetched else { + complete = false; + continue; }; - complete &= fetched.is_ok(); - let Ok(fetched) = fetched else { continue }; + complete &= whole_read; answered = true; note_page(&fetched); for e in fetched { @@ -1947,6 +2015,32 @@ pub(crate) fn record_epoch_minter(cid_hex: &str, epoch: u64, rotator_hex: &str) } } +/// When each epoch's rotation was sent, by its rotator's clock (ms): what an audit dates a +/// Refounding from when its seed snapshot never arrived. +pub(crate) fn epoch_minted_at(cid_hex: &str) -> std::collections::BTreeMap { + crate::db::settings::get_sql_setting(format!("v2_minted_at:{cid_hex}")) + .ok() + .flatten() + .and_then(|v| serde_json::from_str(&v).ok()) + .unwrap_or_default() +} + +/// Remember when `epoch`'s rotation was sent. The earliest wins: a retried Refounding's +/// later chunks don't move it. +pub(crate) fn record_epoch_minted_at(cid_hex: &str, epoch: u64, at_ms: u64) { + if at_ms == 0 { + return; + } + let mut m = epoch_minted_at(cid_hex); + if m.get(&epoch).is_some_and(|held| *held <= at_ms) { + return; + } + m.insert(epoch, at_ms); + if let Ok(v) = serde_json::to_string(&m) { + let _ = crate::db::settings::set_sql_setting(format!("v2_minted_at:{cid_hex}"), v); + } +} + /// Keep `epoch`'s Control Plane address, so its history reads back once the plane has moved on. pub(crate) fn archive_control_address(cid_hex: &str, epoch: u64, control_pk: Option<&PublicKey>) { let Some(pk) = control_pk else { return }; @@ -5604,6 +5698,7 @@ async fn refound_community_with(transport: &T, community: // Recorded here so the local fold agrees with every follower's without // waiting to adopt our own rotation back off the wire. record_epoch_minter(&cid_hex, new_epoch.0, &my_pk.to_hex()); + record_epoch_minted_at(&cid_hex, new_epoch.0, now_ms()); if sever { // Severing: the mark persists FIRST (a crash between it and the revoke // must retry, not forget — B4), then my own links are tombstoned. Other @@ -11883,7 +11978,6 @@ fn fold_control_held(community: &CommunityV2, editions: Vec) -> R /// A Control Plane window a settled follow read this session, which a live edition folds /// against instead of re-reading the plane. -#[derive(Clone)] struct Held { epoch: u64, /// [`super::realtime::link_generation`] when the read began. @@ -11986,12 +12080,15 @@ pub(crate) async fn follow_control_live(community: &CommunityV2, wrap: &Event) - if being_read(community.id()) { return None; } - let held = held_control().lock().unwrap_or_else(|e| e.into_inner()).get(&community.id().0).cloned()?; + // Taken, not copied: every way out below but a repeat either holds the window again or + // leaves a full follow to read a new one. + let held = held_control().lock().unwrap_or_else(|e| e.into_inner()).remove(&community.id().0)?; if held.epoch != community.root_epoch.0 || held.link != super::realtime::link_generation() { return None; } let edition = control::ControlPlane::of(community).open_edition(wrap).ok()?; if held.editions.iter().any(|e| e.inner_id == edition.inner_id) { + held_control().lock().unwrap_or_else(|e| e.into_inner()).entry(community.id().0).or_insert(held); return Some(ControlFollow::default()); } // A Grant of mine that carries the staff key takes a remote signer to open: not on this @@ -13122,7 +13219,7 @@ fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floor let standing = crate::community::roles::RoleIndex::of(&authority.roles); let head_index = HeadIndex::of(&authority.heads); - let mut groups: BTreeMap<(String, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new(); + let mut groups: BTreeMap<(crate::community::edition::EditionText, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new(); for e in editions { groups.entry((e.vsk.clone(), e.entity_id)).or_default().push(e); } @@ -13336,7 +13433,7 @@ fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floor .author .to_bech32() .unwrap_or_else(|_| head.author.to_hex()); - pins_persist.push((channel_hex.clone(), head.content.clone(), head.version, author_npub, head.created_at)); + pins_persist.push((channel_hex.clone(), head.content.to_string(), head.version, author_npub, head.created_at)); } else if let Some(channel_hex) = writers_channel { let ledger = super::writers::Ledger::parse(&head.content).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == *channel_hex); if let Some(ch) = out.channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == *channel_hex) { @@ -13345,7 +13442,7 @@ fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floor changed = true; } } - writers_persist.push((channel_hex.clone(), head.content.clone(), head.version, rebased)); + writers_persist.push((channel_hex.clone(), head.content.to_string(), head.version, rebased)); } } changed |= unseal_held(&mut out); @@ -15712,7 +15809,7 @@ pub async fn follow_rekeys( .await { // Strictly lower only. Equal = the branch we already hold. - Advance::Adopt { new_key, control_pk, control_root, severed, rotator } if new_key < held_before => { + Advance::Adopt { new_key, control_pk, control_root, severed, rotator, at_ms } if new_key < held_before => { crate::log_warn!( "[v2:follow {}] same-epoch fork at epoch {} — converging DOWN onto the canonical sibling", &cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0 @@ -15722,6 +15819,7 @@ pub async fn follow_rekeys( cur.control_root = control_root; // Everything the sibling carries, as if it had been adopted first. record_epoch_minter(&cid_hex, cur.root_epoch.0, &rotator.to_hex()); + record_epoch_minted_at(&cid_hex, cur.root_epoch.0, at_ms); if severed { severed_hops.push(cur.root_epoch.0); // Recorded now: a walk that fails later must not forget it. @@ -15845,12 +15943,13 @@ pub async fn follow_rekeys( let next = Epoch(held_epoch.0.saturating_add(1)); let batches = vec![(base, Some((held_epoch, held_key)))]; match advance_scope(&batches, RekeyScope::Root, cur.id(), &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await { - Advance::Adopt { new_key, control_pk, control_root, severed, rotator } => { + Advance::Adopt { new_key, control_pk, control_root, severed, rotator, at_ms } => { // CORD-02 §5: this npub's snapshot — and only this npub's — // seeds the new epoch's Guestbook. Recorded from the rotation // this device just VERIFIED and adopted, so a snapshot can // never nominate its own author. record_epoch_minter(&cid_hex, next.0, &rotator.to_hex()); + record_epoch_minted_at(&cid_hex, next.0, at_ms); // Record the HOP that was severed, not the walk's final head: // the mark drives both the link condemnation line and the // rescue re-stamp, and a multi-step walk would otherwise @@ -16004,7 +16103,7 @@ enum Advance { /// pair is the BLOB's, never inherited: a legacy 72-byte blob carries /// neither (that epoch's Control folds at the legacy address), and channel /// rotations never carry any. - Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey }, + Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey, at_ms: u64 }, /// A complete owner rotation at `next_epoch` dropped my blob — I'm removed, as of `at_ms`. Removed { at_ms: u64 }, /// No owner rotation extends my held epoch (yet) — keep the current key. @@ -16016,6 +16115,46 @@ enum Advance { } /// Fetch + parse every seal-verified 3303 chunk at a rekey plane address. +/// Where a base rotation may have landed beside the address this client follows: the epoch +/// after next at the held root, and the next epoch at each archived root. Read-only, paged off +/// the relays, so a strand shows whether the rotation exists anywhere this member could read. +pub async fn probe_base_rekey_addresses(transport: &T, community: &CommunityV2) -> Result { + let cid_hex = community.id().to_hex(); + let next = Epoch(community.root_epoch.0.saturating_add(1)); + let mut candidates = vec![ + (format!("e{} @ held root e{}", next.0, community.root_epoch.0), base_rekey_group_key(&community.community_root, community.id(), next)), + (format!("e{} @ held root e{}", next.0 + 1, community.root_epoch.0), base_rekey_group_key(&community.community_root, community.id(), Epoch(next.0 + 1))), + ]; + for (epoch, root) in crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default() { + if root != community.community_root { + candidates.push((format!("e{} @ archived root e{}", epoch.0 + 1, epoch.0), base_rekey_group_key(&root, community.id(), Epoch(epoch.0 + 1)))); + candidates.push((format!("e{} @ archived root e{}", next.0, epoch.0), base_rekey_group_key(&root, community.id(), next))); + } + } + let mut out = Vec::with_capacity(candidates.len()); + for (label, group) in candidates { + let entry = match plane_wraps_paged(transport, &community.relays, &group).await { + Ok(wraps) => { + let chunks: Vec = wraps.iter().filter_map(|w| stream::open_wrap(w, &group).ok()).filter_map(|o| rekey::parse_rekey_chunk(&o).ok()).collect(); + let rotations: Vec = rekey::collect_rotations(&chunks) + .iter() + .map(|r| serde_json::json!({ + "rotator": r.rotator.to_hex(), + "prev_epoch": r.prev_epoch.0, + "new_epoch": r.new_epoch.0, + "scope_is_root": r.scope.id32() == RekeyScope::Root.id32(), + "complete": r.is_complete(), + })) + .collect(); + serde_json::json!({ "address": label, "plane_pk": group.pk_hex(), "wraps": wraps.len(), "chunks": chunks.len(), "rotations": rotations }) + } + Err(e) => serde_json::json!({ "address": label, "plane_pk": group.pk_hex(), "error": e }), + }; + out.push(entry); + } + Ok(serde_json::Value::Array(out)) +} + async fn fetch_rekey_chunks(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result, String> { // A rekey plane address is community_root-derived, so ANY member can seal junk 3303s // there: a flood, or a large community's own multi-chunk rotation, could bury the genuine @@ -16150,6 +16289,8 @@ async fn advance_scope( // Parallel to `winner_severed`: whose Refounding this delivery came from. The // snapshot authority for the adopted epoch (CORD-02 §5) is exactly this npub. let mut winner_rotator: Vec = Vec::new(); + // Parallel too: when that rotation was sent, by its rotator's clock. + let mut winner_at: Vec = Vec::new(); let mut saw_complete_candidate = false; // The latest complete rotation considered: a removal dates from it. let mut removed_at: u64 = 0; @@ -16217,6 +16358,7 @@ async fn advance_scope( winners.push(d); winner_severed.push(scope.id32() == RekeyScope::Root.id32() && r.severed); winner_rotator.push(r.rotator); + winner_at.push(r.at_ms); opened_one = true; break; } @@ -16248,6 +16390,7 @@ async fn advance_scope( control_root: w.control_root, severed: winner_severed[idx], rotator: winner_rotator[idx], + at_ms: winner_at[idx], }; } // A rotation that delivered NO blob to anyone removed nobody. Read literally it @@ -16784,11 +16927,11 @@ pub(crate) fn bench_ledger_chain(n: usize, newest_first: bool) -> std::time::Dur let self_hash = crate::crypto::sha256::digest(&i.to_le_bytes()); editions.push(ParsedEdition { author, - vsk: String::new(), + vsk: "".into(), entity_id: [0; 32], version: i + 1, prev_hash: prev, - content: ledger.to_json(), + content: ledger.to_json().into(), self_hash, created_at: at / 1000, inner_id: self_hash, @@ -17789,11 +17932,11 @@ mod tests { let self_hash = crate::crypto::sha256::digest(&[case.to_le_bytes(), (i as u64).to_le_bytes()].concat()); eds.push(ParsedEdition { author: author.public_key(), - vsk: String::new(), + vsk: "".into(), entity_id: [0; 32], version, prev_hash, - content, + content: content.into(), self_hash, created_at, inner_id: self_hash, @@ -20396,8 +20539,8 @@ mod tests { let fresh = Keys::generate(); grant_roles(&relay, &held, &fresh.public_key(), vec!["d1".repeat(32)]).await.unwrap(); let geid = crate::community::v2::derive::grant_locator(community.id(), &fresh.public_key().to_bytes()); - let window = held_control().lock().unwrap().get(&community.id().0).cloned().expect("still held"); - assert!(window.editions.iter().any(|e| e.entity_id == geid), "our grant is in the window"); + let ours = held_control().lock().unwrap().get(&community.id().0).expect("still held").editions.iter().any(|e| e.entity_id == geid); + assert!(ours, "our grant is in the window"); let v1 = head_hash_on_relay(&relay, &community, &ch.0).await; let now = crate::db::community::load_community_v2(community.id()).unwrap().unwrap(); @@ -23003,6 +23146,33 @@ mod tests { ); } + #[tokio::test(flavor = "multi_thread")] + async fn a_lockdown_without_its_snapshot_is_dated_when_it_was_sent_not_when_adopted() { + let (bed, owner, me) = TestBed::new(); + bed.swap_to(&owner); + let community = create_community(&bed.relay, "LockdownDate", bed.relays.clone(), None).await.unwrap(); + let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None); + let bundle_json = serde_json::to_string(&bundle).unwrap(); + bed.swap_to(&me); + let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap(); + let _ = follow_control(&bed.relay, &joined).await; + let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap(); + + // The owner locks down; no seed snapshot follows. Its chunks say 2,000 s. + let new_root = [0xD7; 32]; + publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await; + let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated + .expect("the owner's lockdown is adopted"); + let cid_hex = crate::simd::hex::bytes_to_hex_32(&updated.id().0); + assert_eq!(epoch_minted_at(&cid_hex).get(&updated.root_epoch.0), Some(&2_000_000), "the rotation's own time is kept"); + + // This device records the lockdown again much later (a re-sync, a fresh login). + add_sever_mark(&cid_hex, updated.root_epoch.0, now_ms() / 1000); + let log = audit_log(&bed.relay, &updated).await.unwrap(); + let entry = log.entries.iter().find(|e| e.action == "keys_rotate").expect("the lockdown shows"); + assert_eq!(entry.at, 2_000_000, "dated when the rotator sent it, the same on every device"); + } + #[tokio::test(flavor = "multi_thread")] async fn a_severing_adopt_never_deadlocks_the_last_link_creator() { // The severance runs INSIDE the follow, which holds `follow_lock` for the @@ -24703,7 +24873,7 @@ mod tests { /// The content of the edition `signer` published for `entity` at `version`. fn content_at(editions: &[ParsedEdition], entity: &[u8; 32], version: u64, signer: &PublicKey) -> (String, Option<[u8; 32]>, [u8; 32]) { let e = editions.iter().find(|e| e.entity_id == *entity && e.version == version && e.author == *signer).expect("the edition"); - (e.content.clone(), e.prev_hash, e.inner_id) + (e.content.to_string(), e.prev_hash, e.inner_id) } #[tokio::test] @@ -34769,7 +34939,7 @@ mod tests { bed.relay.publish(&wrap, &held().relays).await.unwrap(); assert_ne!(x_first, owners); // The lower inner id wins, whoever signed it: what never changes settles the tie. - let ids: Vec<([u8; 32], String)> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk == vsk::WRITERS).map(|e| (e.inner_id, e.content)).collect(); + let ids: Vec<([u8; 32], String)> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk == vsk::WRITERS).map(|e| (e.inner_id, e.content.to_string())).collect(); let winner = ids.iter().min_by_key(|(id, _)| *id).map(|(_, c)| c.clone()).unwrap(); let winner = Ledger::parse(&winner).unwrap(); follow_control(&bed.relay, &held()).await.unwrap(); @@ -38313,6 +38483,35 @@ mod tests { assert!(crate::community::message_delete::in_plane_delete_expiry(&id, scrubbed).await.is_some(), "so its in-plane delete may leave in time"); } + #[tokio::test] + async fn a_poll_takes_one_vote_each_and_both_survive_a_reload() { + let (bed, owner, _member) = TestBed::new(); + bed.swap_to(&owner); + let community = create_community(&bed.relay, "Polls", bed.relays.clone(), None).await.unwrap(); + let general = community.channels[0].id; + let channel_hex = crate::simd::hex::bytes_to_hex_32(&general.0); + let poll = crate::polls::Poll::compose(&["Tacos", "Sushi", "Pizza"], false, None).unwrap(); + let id = try_send_poll_at(&bed.relay, &community, &general, "Lunch?", poll.wire_tags("Lunch?"), next_send_ms()).await.unwrap(); + + let held = crate::state::STATE.lock().await.find_message(&id).map(|(_, m)| m).expect("the poll echoes into the channel"); + assert_eq!(held.content, "Lunch?"); + assert_eq!(held.poll.as_deref().map(|p| p.options.len()), Some(3)); + + // Single choice keeps the first pick only. + send_poll_vote(&bed.relay, &community, &general, &id, 0b110).await.unwrap(); + assert!(send_poll_vote(&bed.relay, &community, &general, &id, 0b001).await.is_err(), "one vote each"); + + let me = nostr_sdk::prelude::ToBech32::to_bech32(&owner.keys.public_key()).unwrap(); + let tally = |m: &crate::types::Message| m.poll.as_ref().unwrap().tally(Some(&me)); + let live = crate::state::STATE.lock().await.find_message(&id).map(|(_, m)| m).unwrap(); + assert_eq!((tally(&live).voters, tally(&live).mine), (1, Some(0b010))); + + let (chat, stored) = crate::db::events::get_message_by_id(&id).await.unwrap().expect("stored"); + assert_eq!(chat, channel_hex); + assert_eq!(stored.poll.as_ref().map(|p| p.options.clone()), held.poll.as_ref().map(|p| p.options.clone())); + assert_eq!(tally(&stored).counts, vec![0, 1, 0], "the vote row folds back in on load"); + } + #[tokio::test] async fn backfill_keeps_the_owner_my_other_devices_derived_and_never_a_strangers() { let (bed, owner, _member) = TestBed::new(); @@ -39964,11 +40163,11 @@ mod folded_chain_tests { let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key()); let edition = |version: u64, hash: u8, prev: Option, author: PublicKey| ParsedEdition { author, - vsk: String::new(), + vsk: "".into(), entity_id: entity, version, prev_hash: prev.map(|p| [p; 32]), - content: String::new(), + content: "".into(), self_hash: [hash; 32], created_at: version * 10, inner_id: [hash; 32], diff --git a/crates/vector-core/src/community/v2/service/audit.rs b/crates/vector-core/src/community/v2/service/audit.rs index 4ab0afe30..41ce49936 100644 --- a/crates/vector-core/src/community/v2/service/audit.rs +++ b/crates/vector-core/src/community/v2/service/audit.rs @@ -623,13 +623,16 @@ fn guestbook_entries(community: &CommunityV2, cid_hex: &str) -> Vec let changes = vec![json!({ "field": "nick", "old": (!old.is_empty()).then_some(old), "new": nick })]; out.push(AuditEntry { id: hex(&ev.rumor_id), at: *at_ms, actor: Some(npub(actor)), action: "member_nick_update", target: Some(member(&target.to_hex())), changes, partial: false }); } - // A Refounding whose seed snapshot never landed still shows, dated when this device adopted it. + // A Refounding whose seed snapshot never landed still shows, dated when its rotator sent it. + // An epoch adopted before that time was recorded falls back to when this device adopted it. + let minted_at = epoch_minted_at(cid_hex); for (epoch, rotator) in &minters { if rotated.contains_key(epoch) { continue; } if let (Some(secs), Ok(pk)) = (severed.get(epoch), PublicKey::from_hex(rotator)) { - rotated.insert(*epoch, (secs.saturating_mul(1000), pk)); + let at = minted_at.get(epoch).copied().unwrap_or_else(|| secs.saturating_mul(1000)); + rotated.insert(*epoch, (at, pk)); } } for (epoch, (at, rotator)) in rotated { @@ -848,11 +851,11 @@ mod tests { self_hash[9..].copy_from_slice(&entity[9..]); ParsedEdition { author: *author, - vsk: vsk.to_string(), + vsk: vsk.into(), entity_id: entity, version, prev_hash: prev.map(|p| p.self_hash), - content: content.to_string(), + content: content.into(), self_hash, created_at: at, inner_id: self_hash, diff --git a/crates/vector-core/src/community/v2/service/control_sync.rs b/crates/vector-core/src/community/v2/service/control_sync.rs index 602a3b1c0..a156a40fc 100644 --- a/crates/vector-core/src/community/v2/service/control_sync.rs +++ b/crates/vector-core/src/community/v2/service/control_sync.rs @@ -257,9 +257,17 @@ fn save(community: &CommunityV2, view: &H, relays: &[String], state.walls.retain(|r, _| relays.contains(r)); state.ghosts.retain(|r, _| relays.contains(r)); state.heal.retain(|r, _| relays.contains(r)); - if let Ok(value) = serde_json::to_string(&state) { - let _ = crate::db::settings::set_sql_setting(view.state_key(&cid_hex), value); + keep_state(view.state_key(&cid_hex), &state); +} + +/// Writes `state` under `key` unless the row already says it: a pass that learned nothing new, +/// most of a boot's passes, leaves the row as it was. Whether it wrote. +fn keep_state(key: String, state: &State) -> bool { + let Ok(value) = serde_json::to_string(state) else { return false }; + if crate::db::settings::get_sql_setting(key.clone()).ok().flatten().as_deref() == Some(value.as_str()) { + return false; } + crate::db::settings::set_sql_setting(key, value).is_ok() } struct Passes; @@ -932,6 +940,23 @@ mod tests { assert_eq!(wall(state(&[("a", Some(900)), ("b", Some(500))], &["b"]), &["a"]), Some(900), "which counts while b answers"); } + #[tokio::test] + async fn a_pass_that_learned_nothing_writes_nothing() { + let (_tmp, _guard) = crate::db::community::test_db(); + let mut s = state(&[("a", Some(900))], &["a"]); + assert!(keep_state("ctl_reads:x".into(), &s), "a first pass writes"); + load_raw("ctl_reads:x"); + let (_, runs) = crate::boot_probe::counting_statements(|| assert!(!keep_state("ctl_reads:x".into(), &s))); + assert_eq!(runs, 0, "an unchanged state, once read, costs no statement"); + s.paged("b", Some(100), false); + assert!(keep_state("ctl_reads:x".into(), &s), "a changed one is written"); + assert_eq!(load_raw("ctl_reads:x"), serde_json::to_string(&s).ok()); + } + + fn load_raw(key: &str) -> Option { + crate::db::settings::get_sql_setting(key.into()).ok().flatten() + } + #[test] fn a_wall_is_kept_at_its_newest_and_cleared_by_a_whole_read_that_meets_none() { let mut s = State::default(); diff --git a/crates/vector-core/src/community/v2/service/sealing.rs b/crates/vector-core/src/community/v2/service/sealing.rs index 2f30ef751..4dd3f83e2 100644 --- a/crates/vector-core/src/community/v2/service/sealing.rs +++ b/crates/vector-core/src/community/v2/service/sealing.rs @@ -74,7 +74,7 @@ pub(crate) async fn seal_history_at(transport: &T, commun return; } // A reaction its author couldn't make no reader counts, so none is kept. - if kind == super::super::kind::REACTION && !roster.channel_permissions(Some(&owner), &author, &hex(&ch.id.0), ch.private).contains(Permissions::ADD_REACTIONS) { + if matches!(kind, super::super::kind::REACTION | super::super::kind::POLL_VOTE) && !roster.channel_permissions(Some(&owner), &author, &hex(&ch.id.0), ch.private).contains(Permissions::ADD_REACTIONS) { return; } if matches!(writing::sort_arrival(judge.as_ref(), event, None), writing::Arrival::Stands(_)) { diff --git a/crates/vector-core/src/community/v2/service/tests/control_sync.rs b/crates/vector-core/src/community/v2/service/tests/control_sync.rs index 35e64d3c1..5aacae7ef 100644 --- a/crates/vector-core/src/community/v2/service/tests/control_sync.rs +++ b/crates/vector-core/src/community/v2/service/tests/control_sync.rs @@ -1745,6 +1745,20 @@ async fn a_relay_that_caps_open_sessions_is_never_written_off_and_every_plane_st assert_eq!(crate::community::transport::plane_reconciles(&relay.url()), Some(true)); } +#[tokio::test] +async fn a_finished_reconcile_has_closed_its_session_before_the_next_opens() { + let l = live(4); + let relay = WireRelay::start().await; + relay.cap_neg_sessions(1); + let reconciler = l.transport.reconciler().unwrap(); + for _ in 0..6 { + let plane = Keys::generate(); + relay.hold(plane_wraps(&plane, 1..=2)); + let answer = reconciler.reconcile(&plane_query(&plane), &[], &relay.url(), 100).await; + assert!(answer.as_ref().is_ok_and(|d| d.need.len() == 2), "one session at a time fits a cap of one: {answer:?}"); + } +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_plane_on_a_relay_that_gates_it_is_read_as_the_plane() { let l = live(4); diff --git a/crates/vector-core/src/compact.rs b/crates/vector-core/src/compact.rs index 371706b79..95e28681e 100644 --- a/crates/vector-core/src/compact.rs +++ b/crates/vector-core/src/compact.rs @@ -1103,7 +1103,6 @@ impl CompactAttachment { } /// Heap bytes held beyond the struct itself (DeepSize). - #[cfg(any(debug_assertions, feature = "bench"))] pub(crate) fn heap_bytes(&self) -> usize { self.url.len() + self.name.len() @@ -1546,7 +1545,6 @@ impl HeldSpan { } } - #[cfg(any(debug_assertions, feature = "bench"))] fn heap_bytes(&self) -> usize { match self { HeldSpan::Color { colors, .. } => colors.heap_bytes(), @@ -1656,10 +1654,70 @@ pub struct MessageExtras { pub addressed_bots: TinyVec, spans: TinyVec, role_mentions: TinyVec<[u8; 32]>, + poll: Option>, /// The newest edit's text is the message content, held there once tail_is_content: bool, } +/// A [`crate::polls::Poll`] with its voters interned. +#[derive(Clone, Debug)] +struct CompactPoll { + multi: bool, + ends_at: Option, + /// `(id, label)` + options: Box<[(Box, Box)]>, + votes: TinyVec, +} + +#[derive(Clone, Debug)] +struct CompactVote { + id: [u8; 32], + voter: u16, + picks: u32, + at: u64, +} + +impl CompactPoll { + fn from_poll(poll: crate::polls::Poll, interner: &mut NpubInterner) -> Self { + Self { + multi: poll.multi, + ends_at: poll.ends_at, + options: poll.options.into_iter().map(|o| (o.id.into_boxed_str(), o.label.into_boxed_str())).collect(), + votes: poll.votes.iter().map(|v| CompactVote::from_vote(v, interner)).collect(), + } + } + + fn to_poll(&self, interner: &NpubInterner) -> crate::polls::Poll { + crate::polls::Poll { + multi: self.multi, + ends_at: self.ends_at, + options: self.options.iter().map(|(id, label)| crate::polls::PollOption { id: id.to_string(), label: label.to_string() }).collect(), + votes: self + .votes + .iter() + .map(|v| crate::polls::PollVote { + id: crate::simd::hex::bytes_to_hex_32(&v.id), + voter: interner.resolve(v.voter).unwrap_or_default().to_string(), + picks: v.picks, + at: v.at, + }) + .collect(), + } + } + + fn heap_bytes(&self) -> usize { + self.options.len() * std::mem::size_of::<(Box, Box)>() + + self.options.iter().map(|(id, label)| id.len() + label.len()).sum::() + + self.votes.heap_bytes() + } +} + +impl CompactVote { + fn from_vote(vote: &crate::polls::PollVote, interner: &mut NpubInterner) -> Self { + Self { id: hex_to_bytes_32(&vote.id), voter: interner.intern(&vote.voter), picks: vote.picks, at: vote.at } + } +} + impl MessageExtras { fn is_empty(&self) -> bool { self.edits.is_empty() @@ -1668,6 +1726,7 @@ impl MessageExtras { && self.addressed_bots.is_empty() && self.spans.is_empty() && self.role_mentions.is_empty() + && self.poll.is_none() } fn edit_history(&self, content: &str) -> Vec { @@ -1683,7 +1742,6 @@ impl MessageExtras { } /// Heap bytes held beyond the box itself (DeepSize). - #[cfg(any(debug_assertions, feature = "bench"))] pub(crate) fn heap_bytes(&self) -> usize { self.edits.heap_bytes() + self.edits.iter().map(|e| e.content.len()).sum::() @@ -1693,6 +1751,7 @@ impl MessageExtras { + self.spans.heap_bytes() + self.spans.iter().map(HeldSpan::heap_bytes).sum::() + self.role_mentions.heap_bytes() + + self.poll.as_ref().map_or(0, |p| std::mem::size_of::() + p.heap_bytes()) } } @@ -1826,6 +1885,17 @@ impl CompactMessage { /// Add a reaction to this message /// (see [`MAX_REACTION_GROUPS`] for the distinct-emoji ceiling) + /// Fold a vote into this message's poll; false when it is no poll or the vote changes nothing. + pub fn add_poll_vote(&mut self, vote: crate::polls::PollVote, interner: &mut NpubInterner) -> bool { + let Some(poll) = self.extras.as_mut().and_then(|x| x.poll.as_mut()) else { return false }; + let id = hex_to_bytes_32(&vote.id); + if vote.picks == 0 || poll.ends_at.is_some_and(|end| vote.at / 1000 > end) || poll.votes.iter().any(|v| v.id == id) { + return false; + } + poll.votes.push(CompactVote::from_vote(&vote, interner)); + true + } + pub fn add_reaction(&mut self, reaction: Reaction, interner: &mut NpubInterner) -> bool { let reaction_id = hex_to_bytes_32(&reaction.id); if self.reactions.iter().any(|r| r.id == reaction_id) { @@ -2326,11 +2396,12 @@ impl CompactMessage { edited_at: e.edited_at, }) .collect(), - preview: msg.preview_metadata.as_ref().map_or_else(TinyVec::new, pack_preview), + preview: msg.preview_metadata.as_deref().map_or_else(TinyVec::new, pack_preview), emoji_tags: intern_emoji_tags(&msg.emoji_tags, interner), addressed_bots: msg.addressed_bots.iter().map(|n| interner.intern(n)).collect(), spans: hold_spans(msg.text_spans), role_mentions: msg.role_mentions.iter().filter_map(|id| crate::simd::hex::hex_to_bytes_32_checked(id)).collect(), + poll: msg.poll.map(|p| Box::new(CompactPoll::from_poll(*p, interner))), tail_is_content, }; Self { @@ -2382,7 +2453,7 @@ impl CompactMessage { content: self.content.to_string(), attachments: self.attachments.iter().map(|a| a.to_attachment()).collect(), edit_history: extras.filter(|x| !x.edits.is_empty()).map(|x| x.edit_history(&self.content)), - preview_metadata: extras.and_then(|x| unpack_preview(x.preview.as_slice())), + preview_metadata: extras.and_then(|x| unpack_preview(x.preview.as_slice())).map(Box::new), emoji_tags: extras.map(|x| resolve_emoji_tags(&x.emoji_tags, interner)).unwrap_or_default(), addressed_bots: extras .map(|x| x.addressed_bots.iter().filter_map(|&i| interner.resolve(i).map(|s| s.to_string())).collect()) @@ -2393,6 +2464,7 @@ impl CompactMessage { .unwrap_or_default(), writer: self.flags.is_writer(), unauthorized: self.flags.is_unauthorized(), + poll: extras.and_then(|x| x.poll.as_deref()).map(|p| Box::new(p.to_poll(interner))), } } } @@ -3489,7 +3561,7 @@ mod tests { replied_to_npub: Some("npub1replier".into()), replied_to_has_attachment: Some(true), replied_to_attachment_extension: None, - preview_metadata: Some(SiteMetadata { + preview_metadata: Some(Box::new(SiteMetadata { domain: "example.com".into(), og_title: Some("Test Page".into()), og_description: Some("A test description".into()), @@ -3499,7 +3571,7 @@ mod tests { title: Some("Test".into()), description: Some("Desc".into()), favicon: Some("https://example.com/favicon.ico".into()), - }), + })), attachments: vec![Attachment { id: "aaaa000000000000000000000000000000000000000000000000000000000000".into(), key: "bbbb000000000000000000000000000000000000000000000000000000000000".into(), @@ -3545,6 +3617,7 @@ mod tests { writer: true, unauthorized: true, text_spans: vec![crate::text_spans::TextSpan::Color(crate::text_color::ColorSpan { from: 0, to: 2, effect: crate::text_color::Effect::Rainbow, colors: Vec::new() })], + poll: None, } } @@ -3609,7 +3682,7 @@ mod tests { assert_eq!(std::mem::size_of::(), 40); assert_eq!(std::mem::size_of::>(), 8); assert_eq!(std::mem::size_of::(), 144); - assert_eq!(std::mem::size_of::(), 56); + assert_eq!(std::mem::size_of::(), 64); assert_eq!(std::mem::size_of::(), 24); assert_eq!(std::mem::size_of::(), 32); } @@ -3883,7 +3956,7 @@ mod tests { }; let msg = Message { id: "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789".into(), - preview_metadata: Some(meta.clone()), + preview_metadata: Some(Box::new(meta.clone())), ..Message::default() }; let mut interner = NpubInterner::new(); @@ -4534,7 +4607,7 @@ mod tests { ]; for meta in cases { assert_eq!(unpack_preview(pack_preview(&meta).as_slice()).as_ref(), Some(&meta)); - let msg = Message { id: hex64(50), preview_metadata: Some(meta.clone()), ..Default::default() }; + let msg = Message { id: hex64(50), preview_metadata: Some(Box::new(meta.clone())), ..Default::default() }; assert_exact(&msg); let mut interner = NpubInterner::new(); let mut c = CompactMessage::from_message(&Message { id: hex64(51), ..Default::default() }, &mut interner); diff --git a/crates/vector-core/src/crypto/batch_verify.rs b/crates/vector-core/src/crypto/batch_verify.rs index 71fc823ab..c97b31487 100644 --- a/crates/vector-core/src/crypto/batch_verify.rs +++ b/crates/vector-core/src/crypto/batch_verify.rs @@ -2,17 +2,47 @@ //! //! One BIP-340 batch equation (nostr-verify) accepts a whole slice of signatures for much //! less than one libsecp256k1 verification each: 1.7x at 16 signatures, 2.2x at 64 on an -//! M4. Parsed keys are cached per thread, so a sender seen before skips its square root. +//! M4. Parsed keys are cached, so a sender seen before skips its square root. //! A slice that fails is narrowed down and its signatures checked one at a time by //! libsecp256k1, so every `false` is the individual verifier's verdict. //! //! Only signatures: callers check the event id first, as `Event::verify` does. use nostr_sdk::prelude::Event; -use std::cell::RefCell; +use std::sync::Mutex; -thread_local! { - static VERIFIER: RefCell = RefCell::new(nostr_verify::Verifier::new()); +/// Verifiers between uses, the most recently used last. Each holds a key cache of about a +/// megabyte: one per thread that ever verified added up to one per core, kept for good. Taken +/// for a use and handed back, the warmest is reused and few are ever made. +static IDLE: Mutex> = Mutex::new(Vec::new()); + +/// Verifiers kept between uses; more made under contention are dropped when done. +const KEPT: usize = 2; + +/// What every verifier has done, summed as each is handed back. +static TOTALS: Mutex = Mutex::new(nostr_verify::Stats { + batches: 0, batches_passed: 0, batched: 0, one_at_a_time: 0, key_hits: 0, key_misses: 0, +}); + +fn with_verifier(f: impl FnOnce(&mut nostr_verify::Verifier) -> R) -> R { + let mut v = IDLE.lock().unwrap_or_else(|e| e.into_inner()).pop().unwrap_or_default(); + let before = v.stats(); + let out = f(&mut v); + let after = v.stats(); + { + let mut t = TOTALS.lock().unwrap_or_else(|e| e.into_inner()); + t.batches += after.batches - before.batches; + t.batches_passed += after.batches_passed - before.batches_passed; + t.batched += after.batched - before.batched; + t.one_at_a_time += after.one_at_a_time - before.one_at_a_time; + t.key_hits += after.key_hits - before.key_hits; + t.key_misses += after.key_misses - before.key_misses; + } + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.len() < KEPT { + idle.push(v); + } + out } /// Whether each event's signature is valid for its id and author, in order. @@ -26,20 +56,26 @@ pub fn signatures(events: &[&Event]) -> Vec { .map(|e| nostr_verify::SigRef { pubkey: e.pubkey.as_bytes(), msg: e.id.as_bytes(), sig: e.sig.as_bytes() }) .collect(); let mut ok = Vec::with_capacity(refs.len()); - VERIFIER.with_borrow_mut(|v| v.verify_batch(&refs, &mut ok)); + with_verifier(|v| v.verify_batch(&refs, &mut ok)); ok } /// Whether one event's signature is valid for its id and author: `Event::verify_signature`, -/// with the author's parsed key from this thread's cache. +/// with the author's parsed key from the cache. pub fn signature(e: &Event) -> bool { let sig = nostr_verify::SigRef { pubkey: e.pubkey.as_bytes(), msg: e.id.as_bytes(), sig: e.sig.as_bytes() }; - VERIFIER.with_borrow_mut(|v| v.verify_one(&sig)) + with_verifier(|v| v.verify_one(&sig)) } -/// This thread's counters: batches and how many held, key-cache hits and misses. +/// Every verifier's counters: batches and how many held, key-cache hits and misses. pub fn stats() -> nostr_verify::Stats { - VERIFIER.with_borrow(|v| v.stats()) + *TOTALS.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Verifiers held between uses. +#[cfg(test)] +fn idle() -> usize { + IDLE.lock().unwrap().len() } #[cfg(test)] @@ -67,4 +103,21 @@ mod tests { assert_eq!(ours.iter().filter(|ok| !**ok).count(), 3); assert!(signatures(&[]).is_empty()); } + + #[test] + fn verifiers_are_shared_and_few_are_kept() { + let keys = Keys::generate(); + let events: Vec = (0..8).map(|i| note(&keys, i)).collect(); + let refs: Vec<&Event> = events.iter().collect(); + let threads: Vec<_> = (0..8).map(|_| { let events = events.clone(); std::thread::spawn(move || { let refs: Vec<&Event> = events.iter().collect(); signatures(&refs) }) }).collect(); + for t in threads { + assert!(t.join().unwrap().iter().all(|ok| *ok)); + } + assert!(idle() <= KEPT, "{} kept", idle()); + let before = stats(); + signatures(&refs); + let after = stats(); + assert_eq!(after.batches, before.batches + 1, "one batch counted"); + assert!(after.key_hits > before.key_hits, "the warm verifier knew the key"); + } } diff --git a/crates/vector-core/src/crypto/mod.rs b/crates/vector-core/src/crypto/mod.rs index 68f5e5c45..1ac6f35db 100644 --- a/crates/vector-core/src/crypto/mod.rs +++ b/crates/vector-core/src/crypto/mod.rs @@ -104,12 +104,72 @@ pub async fn derive_key(password: &str, kdf: &Kdf) -> [u8; 32] { }; let mut output = [0u8; 32]; let params = argon2::Params::new(150_000, 10, 1, Some(32)).unwrap(); + let blocks = params.block_count(); let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params); - argon2.hash_password_into(password.as_bytes(), salt, &mut output).unwrap(); + match Scratch::new(blocks) { + Some(scratch) => argon2.hash_password_into_with_memory(password.as_bytes(), salt, &mut output, scratch).unwrap(), + None => argon2.hash_password_into(password.as_bytes(), salt, &mut output).unwrap(), + } output }).await.unwrap() } +/// Argon2's working memory (~150 MB), mapped for one derive and unmapped the moment it ends. From +/// the heap, malloc kept the freed block for seconds, as footprint, just as the unlocked app +/// began drawing. +struct Scratch { + #[cfg(unix)] + blocks: std::ptr::NonNull, + #[cfg(unix)] + count: usize, +} + +impl Scratch { + #[cfg(unix)] + fn new(count: usize) -> Option { + let len = count.checked_mul(std::mem::size_of::())?; + // SAFETY: a fresh private anonymous mapping, owned by this value until its drop. + let at = unsafe { libc::mmap(std::ptr::null_mut(), len, libc::PROT_READ | libc::PROT_WRITE, libc::MAP_PRIVATE | libc::MAP_ANON, -1, 0) }; + if at == libc::MAP_FAILED { + return None; + } + Some(Self { blocks: std::ptr::NonNull::new(at.cast())?, count }) + } + + #[cfg(not(unix))] + fn new(_count: usize) -> Option { + None + } +} + +#[cfg(unix)] +impl AsMut<[argon2::Block]> for Scratch { + fn as_mut(&mut self) -> &mut [argon2::Block] { + // SAFETY: the mapping holds `count` page-aligned, zero-filled blocks (plain u64 words), + // and is borrowed mutably through this value alone. + unsafe { std::slice::from_raw_parts_mut(self.blocks.as_ptr(), self.count) } + } +} + +#[cfg(not(unix))] +impl AsMut<[argon2::Block]> for Scratch { + fn as_mut(&mut self) -> &mut [argon2::Block] { + &mut [] + } +} + +#[cfg(unix)] +impl Drop for Scratch { + fn drop(&mut self) { + let len = self.count * std::mem::size_of::(); + // SAFETY: the mapping is this value's alone, and nothing borrows it past here. + unsafe { + zeroize::Zeroize::zeroize(std::slice::from_raw_parts_mut(self.blocks.as_ptr().cast::(), len)); + libc::munmap(self.blocks.as_ptr().cast(), len); + } + } +} + /// Seal `plaintext` as `nonce(12) || ciphertext || tag(16)` under a fresh nonce. fn seal_framed(plaintext: &[u8], key: &[u8; 32]) -> Result, chachapoly::Error> { seal_framed_with(&ChaCha20Poly1305::new(key), plaintext) @@ -351,6 +411,12 @@ pub fn mime_from_extension(ext: &str) -> &'static str { "jpg" | "jpeg" => "image/jpeg", "gif" => "image/gif", "webp" => "image/webp", + "jxl" => "image/jxl", + "avif" | "avifs" => "image/avif", + "heic" => "image/heic", + "heif" => "image/heif", + "heics" => "image/heic-sequence", + "heifs" => "image/heif-sequence", "svg" => "image/svg+xml", "bmp" => "image/bmp", "ico" => "image/x-icon", @@ -446,6 +512,12 @@ pub fn extension_from_mime(mime: &str) -> String { "image/jpeg" | "image/jpg" => "jpg", "image/gif" => "gif", "image/webp" => "webp", + "image/jxl" => "jxl", + "image/avif" => "avif", + "image/heic" => "heic", + "image/heif" => "heif", + "image/heic-sequence" => "heics", + "image/heif-sequence" => "heifs", "image/svg+xml" => "svg", "image/bmp" | "image/x-ms-bmp" => "bmp", "image/x-icon" | "image/vnd.microsoft.icon" => "ico", @@ -662,6 +734,12 @@ pub const RECOGNISED_MIMES: &[&str] = &[ "image/x-icon", "image/svg+xml", "image/bmp", + "image/jxl", + "image/avif", + "image/heic", + "image/heif", + "image/heic-sequence", + "image/heif-sequence", "video/webm", "video/x-matroska", "video/quicktime", @@ -721,6 +799,29 @@ pub fn still_png(bytes: &[u8]) -> Result, String> { Ok(out) } +/// A HEIF picture's mime from its `ftyp` brands: the major brand, then the compatible ones. +fn iso_picture(bytes: &[u8]) -> Option<&'static str> { + let size = u32::from_be_bytes(bytes[..4].try_into().ok()?) as usize; + let body = bytes.get(8..size.min(bytes.len()))?; + let brands = std::iter::once(body.get(..4)?).chain(body.get(8..).unwrap_or(&[]).chunks_exact(4)); + let mut seen = None; + for b in brands { + let mime = match b { + b"avif" | b"avis" | b"avio" => return Some("image/avif"), + b"heic" | b"heix" | b"heim" | b"heis" => Some("image/heic"), + b"hevc" | b"hevx" => Some("image/heic-sequence"), + b"mif1" | b"mif2" => Some("image/heif"), + b"msf1" => Some("image/heif-sequence"), + _ => None, + }; + // A specific brand outranks the generic one, and AV1 outranks HEVC. + if mime.is_some() && (seen.is_none() || seen == Some("image/heif") || seen == Some("image/heif-sequence")) { + seen = mime; + } + } + seen +} + pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str { if bytes.len() < 4 { return "application/octet-stream"; @@ -728,6 +829,8 @@ pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str { match bytes[0] { 0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png", 0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg", + 0xFF if bytes[1] == 0x0A => "image/jxl", + 0x00 if bytes.len() >= 12 && bytes[1..12] == *b"\0\0\x0CJXL \r\n\x87\n" => "image/jxl", b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif", b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp", 0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff", @@ -743,10 +846,12 @@ pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str { "video/x-matroska" } } - // ISO base media: the brand sits at offset 4, after a size field. - _ if bytes.len() >= 12 && bytes[4..8] == *b"ftyp" => match &bytes[8..12] { - b"qt " => "video/quicktime", - _ => "video/mp4", + // ISO base media: the brand sits at offset 4, after a size field. HEIF pictures (AVIF, + // HEIC) share the container, so their brands are read first. + _ if bytes.len() >= 12 && bytes[4..8] == *b"ftyp" => match iso_picture(bytes) { + Some(mime) => mime, + None if &bytes[8..12] == b"qt " => "video/quicktime", + None => "video/mp4", }, _ => "application/octet-stream", } @@ -912,6 +1017,24 @@ impl AtRestOpener { maybe_decrypt_blob(stored) } + /// [`Self::open_blob_or_keep`] that opens a blob it owns in place: a failed open checks the + /// tag before touching the buffer, so the fallbacks still see the stored bytes. + pub fn open_blob_owned(&mut self, mut stored: Vec) -> Vec { + if stored.len() == 32 { + return stored; + } + if stored.len() >= NONCE_LEN + TAG_LEN { + if let Some(c) = self.cipher() { + if let Ok(len) = c.open_framed_in_place(&mut stored).map(|p| p.len()) { + stored.copy_within(NONCE_LEN..NONCE_LEN + len, 0); + stored.truncate(len); + return stored; + } + } + } + maybe_decrypt_blob(&stored) + } + /// `maybe_decrypt` for one string, sharing the batch's cipher. #[allow(clippy::result_unit_err)] // maybe_decrypt's own contract, which every caller already handles pub fn open(&mut self, input: String) -> Result { @@ -1315,6 +1438,27 @@ mod tests { mov.extend_from_slice(b"ftypqt "); assert_eq!(mime_from_magic_bytes(&mov), "video/quicktime"); + let ftyp = |major: &[u8; 4], compat: &[u8]| { + let mut b = ((16 + compat.len()) as u32).to_be_bytes().to_vec(); + b.extend_from_slice(b"ftyp"); + b.extend_from_slice(major); + b.extend_from_slice(&[0; 4]); + b.extend_from_slice(compat); + b.extend_from_slice(&[0, 0, 0, 8, b'm', b'e', b't', b'a']); + b + }; + assert_eq!(mime_from_magic_bytes(&ftyp(b"avif", b"mif1miaf")), "image/avif"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"mif1", b"miafavifMA1B")), "image/avif"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"avis", b"msf1")), "image/avif"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"heic", b"mif1heic")), "image/heic"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"mif1", b"heic")), "image/heic"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"msf1", b"hevc")), "image/heic-sequence"); + assert_eq!(mime_from_magic_bytes(&ftyp(b"isom", b"iso2avc1mp41")), "video/mp4"); + for m in ["image/avif", "image/heic", "image/heif", "image/heic-sequence"] { + assert!(RECOGNISED_MIMES.contains(&m), "{m}"); + assert_eq!(mime_from_extension(&extension_from_mime(m)), m); + } + let mut webm = vec![0x1A, 0x45, 0xDF, 0xA3]; webm.extend_from_slice(&[0u8; 20]); webm.extend_from_slice(b"webm"); @@ -1357,6 +1501,12 @@ mod tests { mkv, b"\0\0\0\x14ftypqt ".to_vec(), b"\0\0\0\x20ftypisom".to_vec(), + vec![0xFF, 0x0A, 0x00, 0x00], + b"\0\0\0\x10ftypavif\0\0\0\0".to_vec(), + b"\0\0\0\x10ftypheic\0\0\0\0".to_vec(), + b"\0\0\0\x10ftypmif1\0\0\0\0".to_vec(), + b"\0\0\0\x10ftyphevc\0\0\0\0".to_vec(), + b"\0\0\0\x10ftypmsf1\0\0\0\0".to_vec(), ]; let reachable: std::collections::HashSet<&str> = samples.iter().map(|b| mime_from_magic_bytes(b)).collect(); diff --git a/crates/vector-core/src/db/community.rs b/crates/vector-core/src/db/community.rs index 39cbf6ec6..db969cba2 100644 --- a/crates/vector-core/src/db/community.rs +++ b/crates/vector-core/src/db/community.rs @@ -394,6 +394,18 @@ pub fn converge_server_root_epoch(community_id: &str, epoch: u64, new_root: &[u8 /// returned epoch (`#z` OR-set) so cross-epoch history isn't stranded. Sorted in Rust (not SQL): /// epoch is a u64 stored as i64, so a SQL `ORDER BY` would mis-order epochs >= 2^63. pub fn held_epoch_keys(community_id: &str, scope_id: &str) -> Result, String> { + // Locked, the sealed keys can't open: nothing read then is kept. + if crate::state::is_encryption_enabled_fast() && !crate::state::ENCRYPTION_KEY.has_key() { + return read_epoch_keys(community_id, scope_id); + } + let copy = super::current_session().scoped::(); + copy.get(&super::changes::EPOCH_KEYS, (community_id.to_string(), scope_id.to_string()), || read_epoch_keys(community_id, scope_id)) +} + +struct EpochKeysKey; +type EpochKeysCopy = super::changes::Copy<(String, String), Vec<(Epoch, [u8; 32])>>; + +fn read_epoch_keys(community_id: &str, scope_id: &str) -> Result, String> { let conn = super::get_db_connection_guard_static()?; let mut stmt = conn .prepare("SELECT epoch, key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2") @@ -436,16 +448,7 @@ pub fn history_views(community_id: &str, channel_id: &str) -> Result Result, String> { - let conn = super::get_db_connection_guard_static()?; - let blob: Option> = conn - .query_row( - "SELECT key FROM community_epoch_keys WHERE community_id = ?1 AND scope_id = ?2 AND epoch = ?3", - params![community_id, scope_id, epoch as i64], - |r| r.get(0), - ) - .optional() - .map_err(|e| format!("held epoch key: {e}"))?; - blob.map(|b| dec_key(&b)).transpose() + Ok(held_epoch_keys(community_id, scope_id)?.into_iter().find(|(e, _)| e.0 == epoch).map(|(_, k)| k)) } /// Retain the ephemeral signing key of a message I published, so I can later @@ -1286,6 +1289,24 @@ fn activity_sql(placeholders: &str) -> String { format!("SELECT npub, MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub IS NOT NULL AND npub != '' GROUP BY chat_id, kind, npub") } +/// A Community's member activity table, filled from its history and marked filled, in one +/// write. Rows the triggers wrote meanwhile keep the newer time. +fn fill_member_activity(community_id: &str, chat_ints: &[i64], placeholders: &str) -> Result<(), String> { + let conn = super::get_write_connection_guard_static()?; + let tx = conn.unchecked_transaction().map_err(|e| e.to_string())?; + let sql = format!( + "INSERT INTO community_member_activity (community_id, npub, last_at) \ + SELECT ?, npub, last_at FROM ({}) WHERE true \ + ON CONFLICT (community_id, npub) DO UPDATE SET last_at = MAX(last_at, excluded.last_at)", + activity_sql(placeholders).replacen("SELECT npub, MAX(created_at)", "SELECT npub, MAX(created_at) AS last_at", 1) + ); + let args = std::iter::once(rusqlite::types::Value::Text(community_id.to_string())).chain(chat_ints.iter().map(|i| rusqlite::types::Value::Integer(*i))); + tx.execute(&sql, rusqlite::params_from_iter(args)).map_err(|e| e.to_string())?; + tx.execute("INSERT OR IGNORE INTO community_member_activity (community_id, npub, last_at) VALUES (?1, '', 0)", [community_id]) + .map_err(|e| e.to_string())?; + tx.commit().map_err(|e| e.to_string()) +} + /// The authors with a post that is no sign of membership, one indexed read per kind of sign. /// Binds the Channel rows once per sign. fn flagged_sql(placeholders: &str, strict: bool) -> String { @@ -1299,20 +1320,171 @@ fn flagged_sql(placeholders: &str, strict: bool) -> String { pub(crate) const HELD_POST: &str = "instr(tags, '[\"unauthorized\"]') > 0"; pub(crate) const WRITER_POST: &str = "instr(tags, '[\"writer\"]') > 0"; +/// A presence event's `["event-type", n]`: Some(true) for a join, Some(false) for a leave. +fn presence_kind(tags_json: &str) -> Option { + match crate::event_json::first_tag_value(tags_json, "event-type")?.as_deref() { + Some("1") => Some(true), + Some("0") => Some(false), + _ => None, + } +} + /// `strict`: Grants stamped 0 rather than now, and a post at a writer address no sign of /// presence, since a writer who left still holds a key to post there. -fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result, String> { - let grant_stamp = if strict { 0 } else { now_secs() as u64 }; - /// Cap on rendered members — bounds a presence-flood (fresh-identity 3306 spam) from - /// growing the list / profile-fetch fan-out without limit. - const COMMUNITY_MEMBER_CAP: usize = 500; - use std::collections::HashMap; +/// Each author's newest sign of presence in a Community's channels, and their newest leave: +/// read from its history and kept for the session until the Community's activity generation +/// moves (any post, presence line or flag in its channels, or a channel added or dropped). +fn observed_activity(community_id: &str, strict: bool) -> Result, String> { + let generation = activity_generation(community_id)?; + let copies = super::current_session().scoped::)>>>(); + if let Some((at, kept)) = copies.lock().unwrap_or_else(|e| e.into_inner()).get(&(community_id.to_string(), strict)) { + if *at == generation { + return Ok(kept.clone()); + } + } + let read = match stored_observed(community_id, strict, generation) { + Some(kept) => std::sync::Arc::new(kept), + None => { + let read = read_observed_activity(community_id, strict)?; + store_observed(community_id, strict, generation, &read); + std::sync::Arc::new(read) + } + }; + copies.lock().unwrap_or_else(|e| e.into_inner()).insert((community_id.to_string(), strict), (generation, read.clone())); + Ok(read) +} + +/// The fold stored at `generation`, if the Community hasn't moved since. +fn stored_observed(community_id: &str, strict: bool, generation: i64) -> Option { + use rusqlite::OptionalExtension; + let conn = super::get_db_connection_guard_static().ok()?; + let data: Vec = conn + .prepare_cached("SELECT data FROM community_observed WHERE community_id = ?1 AND strict = ?2 AND gen = ?3") + .and_then(|mut s| s.query_row(params![community_id, strict, generation], |r| r.get(0)).optional()) + .ok()??; + drop(conn); + observed_from_bytes(&data) +} - // The owner is seeded by `fold_members`, which derives it from the community id. - if !community_held(&CommunityId(hex_id_to_32(community_id)?))? { - return Ok(Vec::new()); +/// Folds while a sync moves the Community come every few seconds: only the first of a stretch +/// is stored, since a later login reads it back only if nothing moved after it. +fn store_observed(community_id: &str, strict: bool, generation: i64, observed: &Observed) { + struct StoredAt; + type Stored = std::sync::Mutex>; + let stored = super::current_session().scoped::(); + let key = (community_id.to_string(), strict); + if stored.lock().unwrap_or_else(|e| e.into_inner()).get(&key).is_some_and(|at| at.elapsed() < std::time::Duration::from_secs(60)) { + return; } + if write_observed(community_id, strict, generation, observed) { + stored.lock().unwrap_or_else(|e| e.into_inner()).insert(key, web_time::Instant::now()); + } +} +fn write_observed(community_id: &str, strict: bool, generation: i64, observed: &Observed) -> bool { + let Ok(conn) = super::get_write_connection_guard_static() else { return false }; + conn.execute( + "INSERT OR REPLACE INTO community_observed (community_id, strict, gen, data) VALUES (?1, ?2, ?3, ?4)", + params![community_id, strict, generation, observed_to_bytes(observed)], + ) + .is_ok() +} + +/// Two author maps as bytes: per map a count, then per author a 32-byte key (or a length-prefixed +/// name for one that isn't a key) and its time, all integers LEB128. +fn observed_to_bytes((active, left): &Observed) -> Vec { + fn uleb(out: &mut Vec, mut n: u64) { + loop { + let b = (n & 0x7f) as u8; + n >>= 7; + if n == 0 { + out.push(b); + return; + } + out.push(b | 0x80); + } + } + let mut out = Vec::with_capacity(1 + (active.len() + left.len()) * 38); + out.push(1); + for map in [active, left] { + uleb(&mut out, map.len() as u64); + for (npub, at) in map { + match PublicKey::parse(npub).ok().filter(|pk| pk.to_bech32().ok().as_deref() == Some(npub.as_str())) { + Some(pk) => { + out.push(0); + out.extend_from_slice(&pk.to_bytes()); + } + None => { + out.push(1); + uleb(&mut out, npub.len() as u64); + out.extend_from_slice(npub.as_bytes()); + } + } + uleb(&mut out, *at); + } + } + out +} + +fn observed_from_bytes(bytes: &[u8]) -> Option { + fn uleb(b: &mut &[u8]) -> Option { + let mut n = 0u64; + for shift in (0..64).step_by(7) { + let (&byte, rest) = b.split_first()?; + *b = rest; + n |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + return Some(n); + } + } + None + } + let (&1, mut b) = bytes.split_first()? else { return None }; + let mut maps: [std::collections::HashMap; 2] = Default::default(); + for map in &mut maps { + let n = uleb(&mut b)? as usize; + map.reserve(n.min(1 << 16)); + for _ in 0..n { + let (&tag, rest) = b.split_first()?; + b = rest; + let npub = match tag { + 0 => { + let (key, rest) = (b.get(..32)?, b.get(32..)?); + b = rest; + PublicKey::from_slice(key).ok()?.to_bech32().ok()? + } + 1 => { + let len = uleb(&mut b)? as usize; + let (name, rest) = (b.get(..len)?, b.get(len..)?); + b = rest; + String::from_utf8(name.to_vec()).ok()? + } + _ => return None, + }; + map.insert(npub, uleb(&mut b)?); + } + } + b.is_empty().then(|| { let [a, l] = maps; (a, l) }) +} + +struct ObservedKey; + +/// (newest activity, newest leave) by author. +type Observed = (std::collections::HashMap, std::collections::HashMap); + +/// Read before the history it stands for, so a write landing between the two leaves the copy +/// older than the generation, never newer. +fn activity_generation(community_id: &str) -> Result { + use rusqlite::OptionalExtension; + let conn = super::get_db_connection_guard_static()?; + conn.prepare_cached("SELECT gen FROM community_activity_gen WHERE community_id = ?1") + .and_then(|mut s| s.query_row([community_id], |r| r.get(0)).optional()) + .map(|g| g.unwrap_or(0)) + .map_err(|e| e.to_string()) +} + +fn read_observed_activity(community_id: &str, strict: bool) -> Result { + use std::collections::HashMap; let chat_ints = community_chat_row_ids(community_id)?; // APPLICATION_SPECIFIC (30078) is the kind for presence/system events; everything else in a @@ -1328,21 +1500,29 @@ fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result>().join(","); { - // Each author's newest across Channels and kinds is taken here. - let mut stmt = conn.prepare(&activity_sql(&placeholders)).map_err(|e| e.to_string())?; + // Each author's newest across Channels and kinds: the table the events triggers keep, + // filled from the history once. + let filled: bool = conn + .query_row("SELECT EXISTS(SELECT 1 FROM community_member_activity WHERE community_id = ?1 AND npub = '')", [community_id], |r| r.get(0)) + .map_err(|e| e.to_string())?; + if !filled { + drop(conn); + fill_member_activity(community_id, &chat_ints, &placeholders)?; + conn = super::get_db_connection_guard_static()?; + } + let mut stmt = conn + .prepare_cached("SELECT npub, last_at FROM community_member_activity WHERE community_id = ?1 AND npub != ''") + .map_err(|e| e.to_string())?; let rows = stmt - .query_map(rusqlite::params_from_iter(chat_ints.iter()), |r| { - Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64)) - }) + .query_map([community_id], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64))) .map_err(|e| e.to_string())?; for row in rows { let (npub, at) = row.map_err(|e| e.to_string())?; - let newest = active.entry(npub).or_insert(at); - *newest = (*newest).max(at); + active.insert(npub, at); } } @@ -1353,15 +1533,27 @@ fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result = stmt.query_map(rusqlite::params_from_iter(binds), |r| r.get(0)).map_err(|e| e.to_string())?.flatten().collect(); - let sql = format!("SELECT MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} AND npub = ? AND NOT {excluded}"); - for npub in flagged { + drop(stmt); + if !flagged.is_empty() { + // Every flagged author's newest post that is a sign, in one read rather than one each. + let sql = format!( + "SELECT npub, MAX(created_at) FROM events WHERE chat_id IN ({placeholders}) AND kind != {sys} \ + AND npub IN (SELECT value FROM json_each(?)) AND NOT {excluded} GROUP BY npub" + ); let mut args: Vec = chat_ints.iter().map(|i| rusqlite::types::Value::Integer(*i)).collect(); - args.push(npub.clone().into()); - let newest: Option = conn.query_row(&sql, rusqlite::params_from_iter(args), |r| r.get(0)).map_err(|e| e.to_string())?; - match newest { - Some(at) => active.insert(npub, at.max(0) as u64), - None => active.remove(&npub), - }; + args.push(serde_json::to_string(&flagged).map_err(|e| e.to_string())?.into()); + let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?; + let newest: HashMap = stmt + .query_map(rusqlite::params_from_iter(args), |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64))) + .map_err(|e| e.to_string())? + .collect::>() + .map_err(|e| e.to_string())?; + for npub in flagged { + match newest.get(&npub) { + Some(at) => active.insert(npub, *at), + None => active.remove(&npub), + }; + } } } @@ -1374,37 +1566,49 @@ fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result(0)?, r.get::<_, i64>(1)?.max(0) as u64, r.get::<_, String>(2)?)) + // SystemEventType: 1 = MemberJoined, 0 = MemberLeft (carried in an ["event-type", n] tag). + let etype = match r.get_ref(2)? { + rusqlite::types::ValueRef::Text(b) if let Ok(tags) = std::str::from_utf8(b) => presence_kind(tags), + _ => presence_kind(&r.get::<_, String>(2)?), + }; + Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?.max(0) as u64, etype)) }) .map_err(|e| e.to_string())? .collect::, _>>() .map_err(|e| e.to_string())?; - // The reader goes back before every presence event's tags are parsed. drop(stmt); drop(conn); - for (npub, at, tags_json) in rows { - // SystemEventType: 1 = MemberJoined, 0 = MemberLeft (carried in an ["event-type", n] tag). - let etype = serde_json::from_str::>>(&tags_json) - .ok() - .and_then(|tags| { - tags.into_iter() - .find(|t| t.first().map(|s| s == "event-type").unwrap_or(false)) - .and_then(|t| t.into_iter().nth(1)) - }); - match etype.as_deref() { - Some("1") => { + for (npub, at, etype) in rows { + match etype { + Some(true) => { let e = active.entry(npub).or_insert(0); if at > *e { *e = at; } } - Some("0") => { + Some(false) => { let e = left.entry(npub).or_insert(0); if at > *e { *e = at; } } - _ => {} + None => {} } } } } + Ok((active, left)) +} + +fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result, String> { + let grant_stamp = if strict { 0 } else { now_secs() as u64 }; + /// Cap on rendered members — bounds a presence-flood (fresh-identity 3306 spam) from + /// growing the list / profile-fetch fan-out without limit. + const COMMUNITY_MEMBER_CAP: usize = 500; + + // The owner is seeded by `fold_members`, which derives it from the community id. + if !community_held(&CommunityId(hex_id_to_32(community_id)?))? { + return Ok(Vec::new()); + } + + let observed = observed_activity(community_id, strict)?; + let (active, left) = (&observed.0, &observed.1); // Events store bech32, so compare on bech32. let banned: std::collections::HashSet = banned_set(community_id) @@ -1415,8 +1619,9 @@ fn member_activity(community_id: &str, capped: bool, strict: bool) -> Result = active - .into_iter() - .filter(|(npub, at)| !banned.contains(npub) && left.get(npub).is_none_or(|l| at >= l)) + .iter() + .filter(|(npub, at)| !banned.contains(*npub) && left.get(*npub).is_none_or(|l| *at >= l)) + .map(|(npub, at)| (npub.clone(), *at)) .collect(); // RE-ASSERT authorized members AFTER the activity/leave filter: the proven owner + every @@ -2745,13 +2950,18 @@ pub fn community_image(community_id: &str, banner: bool) -> Result Result { - let conn = super::get_db_connection_guard_static()?; - conn.query_row("SELECT 1 FROM communities WHERE community_id = ?1", params![id.to_hex()], |_| Ok(())) - .optional() - .map(|row| row.is_some()) - .map_err(|e| e.to_string()) + let copy = super::current_session().scoped::>(); + copy.get(&super::changes::COMMUNITY, id.0, || { + let conn = super::get_db_connection_guard_static()?; + conn.query_row("SELECT 1 FROM communities WHERE community_id = ?1", params![id.to_hex()], |_| Ok(())) + .optional() + .map(|row| row.is_some()) + .map_err(|e| e.to_string()) + }) } +struct HeldKey; + /// The persisted CORD-02 §6 stash riding a community row: the vsk-0 fields /// Vector doesn't drive but must republish verbatim on its own edits. #[derive(serde::Serialize, serde::Deserialize, Default)] @@ -2990,7 +3200,20 @@ pub fn presence_lines_shown_in(channel_id: &str) -> Result { } /// Load a v2 community by id, or `None` if absent / not a v2 community. +struct CommunityCopyKey; +type CommunityCopy = super::changes::Copy<[u8; 32], Option>; + +/// A held Community as its rows say, opened once a session until one of its rows is written. pub fn load_community_v2(id: &CommunityId) -> Result, String> { + // Locked, its sealed rows can't open: nothing read then is kept. + if crate::state::is_encryption_enabled_fast() && !crate::state::ENCRYPTION_KEY.has_key() { + return read_community_v2(id); + } + let copy = super::current_session().scoped::(); + copy.get(&super::changes::COMMUNITY, id.0, || read_community_v2(id)) +} + +fn read_community_v2(id: &CommunityId) -> Result, String> { use crate::community::v2::community::{ChannelV2, CommunityV2}; use crate::community::v2::control::CommunityIdentity; let conn = super::get_db_connection_guard_static()?; @@ -3034,13 +3257,13 @@ pub fn load_community_v2(id: &CommunityId) -> Result = serde_json::from_str(&dt(o, &relays_e)).unwrap_or_default(); + let relays: Vec = serde_json::from_str(&dt(o, relays_e)).unwrap_or_default(); let mut channels = Vec::new(); { @@ -3069,12 +3292,12 @@ pub fn load_community_v2(id: &CommunityId) -> Result Result Result(&j).ok()); let banner = banner_e - .map(|s| dt(o, &s)) + .map(|s| dt(o, s)) .and_then(|j| serde_json::from_str::(&j).ok()); let stash: CommunityMetaStash = stash_e - .map(|s| dt(o, &s)) + .map(|s| dt(o, s)) .and_then(|j| serde_json::from_str(&j).ok()) .unwrap_or_default(); @@ -3125,9 +3348,7 @@ pub fn load_community_v2(id: &CommunityId) -> Result dk(o, &blob).ok().filter(|cr| { crate::community::v2::derive::control_signer_group_key(cr, id, Epoch(root_epoch as u64)).pk() == pk @@ -3141,8 +3362,8 @@ pub fn load_community_v2(id: &CommunityId) -> Result Result<(Vec = { + let conn = crate::db::get_db_connection_guard_static().unwrap(); + let mut stmt = conn.prepare("SELECT community_id FROM communities").unwrap(); + stmt.query_map([], |r| r.get(0)).unwrap().flatten().collect() + }; + for pass in 0..2 { + for strict in [false, true] { + let t = std::time::Instant::now(); + let mut slowest = std::time::Duration::ZERO; + for id in &ids { + let one = std::time::Instant::now(); + let _ = if strict { community_member_activity_strict(id) } else { community_member_activity(id) }; + slowest = slowest.max(one.elapsed()); + } + println!("pass {pass} strict {strict}: {} communities in {:?}, slowest {:?}", ids.len(), t.elapsed(), slowest); + } + } + }) + .await; + } + static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); /// A unique, syntactically-valid test npub per call (bech32 charset, correct @@ -3540,7 +3790,7 @@ mod tests { format!("npub1{}", std::str::from_utf8(&payload).unwrap()) } - fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) { + pub(super) fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) { let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner()); crate::db::close_database(); // Per-account row-id caches survive close_database; clear them so a stale entry from a prior @@ -3648,6 +3898,319 @@ mod tests { assert_eq!(kept_in(&welcome), 3); } + /// Not a check: member activity on a Community with a long history, read whole as before and + /// from the table, and what the triggers add to storing posts. + /// `cargo nextest run -p vector-core member_activity_at_scale --run-ignored only --no-capture` + #[tokio::test] + #[ignore] + async fn member_activity_at_scale() { + let (_tmp, _guard) = init_test_db(); + let (_c, cid, general) = saved_v2("Large"); + let seed = crate::types::Message { id: "seed".into(), content: "x".into(), at: 1000, npub: Some(Keys::generate().public_key().to_bech32().unwrap()), ..Default::default() }; + crate::db::events::save_message(&general, &seed).await.unwrap(); + let fill = |rows: i64, triggers: bool| { + let conn = crate::db::get_write_connection_guard_static().unwrap(); + if !triggers { + conn.execute_batch("DROP TRIGGER community_member_activity_insert;").unwrap(); + } + let t = std::time::Instant::now(); + conn.execute( + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?1) \ + INSERT INTO events (id, kind, chat_id, user_id, content, tags, created_at, received_at, mine, pending, failed, npub) \ + SELECT lower(hex(randomblob(32))), kind, chat_id, user_id, content || hex(randomblob(300)), tags, created_at + i, received_at, 0, 0, 0, 'npub1member' || (i % 2000) \ + FROM events, n WHERE id = 'seed'", + [rows], + ) + .unwrap(); + t.elapsed() + }; + let with = fill(150_000, true); + let without = fill(150_000, false); + println!("insert 150k posts: with triggers {with:?}, without {without:?}"); + let chats = community_chat_row_ids(&cid).unwrap(); + let placeholders = chats.iter().map(|_| "?").collect::>().join(","); + { + let conn = crate::db::get_db_connection_guard_static().unwrap(); + let t = std::time::Instant::now(); + let mut stmt = conn.prepare(&activity_sql(&placeholders)).unwrap(); + let n = stmt.query_map(rusqlite::params_from_iter(chats.iter()), |_| Ok(())).unwrap().count(); + println!("whole-history read (before, every session): {:?} for {n} groups", t.elapsed()); + } + { + let conn = crate::db::get_write_connection_guard_static().unwrap(); + conn.execute("DELETE FROM community_member_activity WHERE community_id = ?1", [&cid]).unwrap(); + } + let t = std::time::Instant::now(); + let first = community_member_activity_capped(&cid, false).unwrap().len(); + println!("first read, fills the table once: {:?} ({first} members)", t.elapsed()); + let t = std::time::Instant::now(); + community_member_activity_capped(&cid, false).unwrap(); + println!("later reads, from the table: {:?}", t.elapsed()); + crate::db::get_write_connection_guard_static().unwrap() + .execute("UPDATE events SET tags = '[[\"unauthorized\"]]' WHERE rowid % 20 = 0", []).unwrap(); + // The census's rate: 183 asks in a boot, the history read each time and kept. + let t = std::time::Instant::now(); + for _ in 0..183 { + read_observed_activity(&cid, false).unwrap(); + } + println!("183 asks, read each time: {:?}", t.elapsed()); + let t = std::time::Instant::now(); + for _ in 0..183 { + community_member_activity_capped(&cid, false).unwrap(); + } + println!("183 asks, kept: {:?}", t.elapsed()); + // A later login: the fold read back from its stored row instead of the history. + let generation = activity_generation(&cid).unwrap(); + let t = std::time::Instant::now(); + let folded = read_observed_activity(&cid, false).unwrap(); + println!("a login's first fold, from the history: {:?}", t.elapsed()); + write_observed(&cid, false, generation, &folded); + let t = std::time::Instant::now(); + let back = stored_observed(&cid, false, generation).unwrap(); + println!("a login's first fold, read back: {:?} ({} members, {} bytes)", t.elapsed(), back.0.len(), observed_to_bytes(&back).len()); + } + + /// The session's copies of settings, Communities and Control wrap ids follow every write: + /// through the helpers, through raw SQL, and one a reader copied before its commit. + #[tokio::test] + async fn read_copies_follow_every_write() { + use crate::db::settings::{get_sql_setting, set_sql_setting}; + let (_tmp, _guard) = init_test_db(); + set_sql_setting("copy_probe".into(), "one".into()).unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("one")); + set_sql_setting("copy_probe".into(), "two".into()).unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("two"), "through the helper"); + crate::db::get_write_connection_guard_static().unwrap() + .execute("UPDATE settings SET value = 'three' WHERE key = 'copy_probe'", []).unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("three"), "through raw SQL"); + { + // Read (and copied) while a write sits uncommitted: the commit still shows. + let w = crate::db::get_write_connection_guard_static().unwrap(); + w.execute_batch("BEGIN; UPDATE settings SET value = 'four' WHERE key = 'copy_probe';").unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("three")); + w.execute_batch("COMMIT;").unwrap(); + } + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("four"), "after the commit"); + + // A row written through the helpers drops that row's copy alone. + set_sql_setting("copy_other".into(), "kept".into()).unwrap(); + assert_eq!(get_sql_setting("copy_other".into()).unwrap().as_deref(), Some("kept")); + set_sql_setting("copy_probe".into(), "five".into()).unwrap(); + let (_, runs) = crate::boot_probe::counting_statements(|| { + assert_eq!(get_sql_setting("copy_other".into()).unwrap().as_deref(), Some("kept")); + }); + assert_eq!(runs, 0, "another row's write keeps this row's copy"); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("five")); + crate::db::settings::remove_setting("copy_probe").unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap(), None, "a removed row"); + crate::db::settings::advance_u64_setting("copy_probe".into(), 7).unwrap(); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("7"), "an advanced row"); + { + // A helper write inside a transaction: the row's copy waits for the commit too. + let w = crate::db::get_write_connection_guard_static().unwrap(); + w.execute_batch("BEGIN;").unwrap(); + crate::db::changes::writing_setting("copy_probe", || w.execute("UPDATE settings SET value = '8' WHERE key = 'copy_probe'", []).unwrap()); + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("7")); + w.execute_batch("COMMIT;").unwrap(); + } + assert_eq!(get_sql_setting("copy_probe".into()).unwrap().as_deref(), Some("8"), "after that commit"); + + let (mut c, cid, _) = saved_v2("Before"); + let id = c.identity.community_id; + assert_eq!(load_community_v2(&id).unwrap().unwrap().name, "Before"); + c.name = "After".into(); + save_community_v2(&c).unwrap(); + assert_eq!(load_community_v2(&id).unwrap().unwrap().name, "After", "a renamed Community"); + assert!(community_held(&id).unwrap()); + crate::db::get_write_connection_guard_static().unwrap().execute("DELETE FROM communities WHERE community_id = ?1", [id.to_hex()]).unwrap(); + assert!(!community_held(&id).unwrap(), "a left Community"); + save_community_v2(&c).unwrap(); + assert!(community_held(&id).unwrap(), "and joined again"); + + let view = [9u8; 32]; + assert!(control_wrap_ids(&cid, &view).unwrap().is_empty()); + store_control_wraps(&cid, &view, 0, 100, &[([1u8; 32], 50, Some(vec![1, 2, 3]))]).unwrap(); + assert_eq!(control_wrap_ids(&cid, &view).unwrap().len(), 1, "a stored Control wrap"); + assert_eq!(control_wrap_counts(&cid, &view).unwrap().0, 1); + store_control_wraps(&cid, &view, 0, 100, &[([2u8; 32], 60, Some(vec![4, 5]))]).unwrap(); + assert_eq!(control_wrap_counts(&cid, &view).unwrap(), (2, 0, 5), "counts after another wrap"); + + assert_eq!(held_epoch_key(&cid, "scope", 1).unwrap(), None); + store_epoch_key(&cid, "scope", 1, &[7u8; 32]).unwrap(); + assert_eq!(held_epoch_key(&cid, "scope", 1).unwrap(), Some([7u8; 32]), "a stored epoch key"); + store_epoch_key(&cid, "scope", 2, &[8u8; 32]).unwrap(); + assert_eq!(held_epoch_keys(&cid, "scope").unwrap().len(), 2, "and the next epoch's"); + } + + /// The census's repeat reads at the rates a real boot showed, read each time and through the + /// session copies. + /// `cargo nextest run -p vector-core read_copies_at_census_rates --run-ignored only --no-capture` + #[tokio::test] + #[ignore] + async fn read_copies_at_census_rates() { + use crate::db::settings::{get_sql_setting, set_sql_setting}; + let (_tmp, _guard) = init_test_db(); + let keys: Vec = (0..40).map(|i| format!("bench_key_{i}")).collect(); + for k in &keys { + set_sql_setting(k.clone(), "v".into()).unwrap(); + } + let (c, cid, _) = saved_v2("Bench"); + let id = c.identity.community_id; + let view = [7u8; 32]; + let wraps: Vec<_> = (0..200u8).map(|i| ([i; 32], 50 + i as u64, Some(vec![1, 2, 3]))).collect(); + store_control_wraps(&cid, &view, 0, 1000, &wraps).unwrap(); + let (settings, communities, controls) = (9_200, 2_600, 3_400); + let read_setting = |k: &str| -> Option { + let conn = crate::db::get_db_connection_guard_static().unwrap(); + conn.query_row("SELECT value FROM settings WHERE key = ?1", [k], |r| r.get(0)).ok() + }; + let (each, each_runs) = crate::boot_probe::counting_statements(|| { + for i in 0..settings { read_setting(&keys[i % keys.len()]); } + for _ in 0..communities { read_community_v2(&id).unwrap(); } + for _ in 0..controls { read_control_wrap_ids(&cid, &view).unwrap(); } + }); + let (copied, copied_runs) = crate::boot_probe::counting_statements(|| { + for i in 0..settings { get_sql_setting(keys[i % keys.len()].clone()).unwrap(); } + for _ in 0..communities { load_community_v2(&id).unwrap(); } + for _ in 0..controls { control_wrap_ids(&cid, &view).unwrap(); } + }); + println!( + "{settings} settings + {communities} Community loads + {controls} Control wrap reads: \ + read each time {each:?} in {each_runs} statements, copied {copied:?} in {copied_runs}" + ); + } + + /// The member activity table holds what a read of the whole history finds, as posts land + /// and are deleted, before and after it is first filled. + #[tokio::test] + async fn member_activity_table_matches_the_history() { + let (_tmp, _guard) = init_test_db(); + let (_c, cid, general) = saved_v2("Busy"); + let (a, b) = (Keys::generate().public_key().to_bech32().unwrap(), Keys::generate().public_key().to_bech32().unwrap()); + let post = |id: &str, secs: u64, who: &str| crate::types::Message { + id: id.into(), content: "x".into(), at: secs * 1000, npub: Some(who.to_string()), ..Default::default() + }; + let from_history = || -> std::collections::BTreeMap { + let chats = community_chat_row_ids(&cid).unwrap(); + let conn = crate::db::get_db_connection_guard_static().unwrap(); + let placeholders = chats.iter().map(|_| "?").collect::>().join(","); + let mut stmt = conn.prepare(&activity_sql(&placeholders)).unwrap(); + let mut out = std::collections::BTreeMap::new(); + for row in stmt.query_map(rusqlite::params_from_iter(chats.iter()), |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? as u64))).unwrap() { + let (n, at) = row.unwrap(); + let e = out.entry(n).or_insert(at); + *e = (*e).max(at); + } + out + }; + let in_table = || -> std::collections::BTreeMap { + let conn = crate::db::get_db_connection_guard_static().unwrap(); + let mut stmt = conn.prepare("SELECT npub, last_at FROM community_member_activity WHERE community_id = ?1 AND npub != ''").unwrap(); + stmt.query_map([&cid], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? as u64))).unwrap().map(Result::unwrap).collect() + }; + crate::db::events::save_message(&general, &post("a1", 100, &a)).await.unwrap(); + crate::db::events::save_message(&general, &post("b1", 200, &b)).await.unwrap(); + // Read once: filled from the history. + community_member_activity(&cid).unwrap(); + assert_eq!(in_table(), from_history()); + // New posts after the fill are kept by the triggers. + crate::db::events::save_message(&general, &post("a2", 300, &a)).await.unwrap(); + assert_eq!(in_table(), from_history()); + assert_eq!(in_table().get(&a), Some(&300)); + // Deleting a member's newest post falls back to their one before it; their last, to none. + crate::db::events::delete_event("a2").await.unwrap(); + assert_eq!(in_table(), from_history()); + assert_eq!(in_table().get(&a), Some(&100)); + crate::db::events::delete_event("b1").await.unwrap(); + assert_eq!(in_table(), from_history()); + assert!(!in_table().contains_key(&b)); + } + + #[test] + fn observed_activity_bytes_round_trip() { + let key = Keys::generate().public_key().to_bech32().unwrap(); + let mut active = std::collections::HashMap::new(); + active.insert(key.clone(), 1_700_000_000u64); + active.insert("not-a-key".to_string(), 0); + let mut left = std::collections::HashMap::new(); + left.insert(key.clone(), u64::MAX); + let observed = (active, left); + let bytes = observed_to_bytes(&observed); + assert_eq!(observed_from_bytes(&bytes), Some(observed.clone())); + assert!(bytes.len() < 2 * (1 + 32 + 10) + 20, "{} bytes", bytes.len()); + assert_eq!(observed_from_bytes(&bytes[..bytes.len() - 1]), None, "a truncated row is not read"); + assert_eq!(observed_from_bytes(&observed_to_bytes(&Default::default())), Some(Default::default())); + } + + /// The fold is stored against the Community's activity count, read back while it holds, and + /// not once the Community moves. + #[tokio::test] + async fn a_stored_fold_is_read_back_until_the_community_moves() { + let (_tmp, _guard) = init_test_db(); + let (_c, cid, general) = saved_v2("Stored"); + let a = Keys::generate().public_key().to_bech32().unwrap(); + let post = |id: &str, secs: u64| crate::types::Message { + id: id.into(), content: "x".into(), at: secs * 1000, npub: Some(a.clone()), ..Default::default() + }; + crate::db::events::save_message(&general, &post("s1", 100)).await.unwrap(); + let generation = activity_generation(&cid).unwrap(); + let folded = observed_activity(&cid, false).unwrap(); + assert_eq!(stored_observed(&cid, false, generation).as_ref(), Some(&*folded), "stored as folded"); + crate::db::events::save_message(&general, &post("s2", 200)).await.unwrap(); + let moved = activity_generation(&cid).unwrap(); + assert_ne!(moved, generation); + assert_eq!(stored_observed(&cid, false, moved), None, "a moved Community folds again"); + delete_community_v2_for_test(&cid); + assert_eq!(stored_observed(&cid, false, generation), None, "and a left one keeps nothing"); + } + + fn delete_community_v2_for_test(cid: &str) { + crate::db::get_write_connection_guard_static().unwrap().execute("DELETE FROM communities WHERE community_id = ?1", [cid]).unwrap(); + } + + /// The session's copy of a Community's member activity matches a fresh read of its history + /// after every kind of change that can move it, and a change elsewhere keeps it. + #[tokio::test] + async fn kept_member_activity_follows_every_change() { + use crate::stored_event::SystemEventType::{MemberJoined, MemberLeft}; + let (_tmp, _guard) = init_test_db(); + let (_c, cid, general) = saved_v2("Watched"); + let (_o, other_cid, other) = saved_v2("Elsewhere"); + let (a, b) = (Keys::generate().public_key().to_bech32().unwrap(), Keys::generate().public_key().to_bech32().unwrap()); + let post = |id: &str, secs: u64, who: &str| crate::types::Message { + id: id.into(), content: "x".into(), at: secs * 1000, npub: Some(who.to_string()), ..Default::default() + }; + let current = |strict: bool| { + let kept = observed_activity(&cid, strict).unwrap(); + let fresh = read_observed_activity(&cid, strict).unwrap(); + assert_eq!(*kept, fresh, "strict {strict}"); + kept + }; + let same = |was: &std::sync::Arc| std::sync::Arc::ptr_eq(was, &observed_activity(&cid, false).unwrap()); + + crate::db::events::save_message(&general, &post("a1", 100, &a)).await.unwrap(); + let first = current(false); + current(true); + assert!(same(&first), "nothing changed: the copy is kept"); + + crate::db::events::save_message(&other, &post("o1", 150, &b)).await.unwrap(); + assert!(same(&first), "a post in another Community keeps it"); + let _ = other_cid; + + crate::db::events::save_message(&general, &post("b1", 200, &b)).await.unwrap(); + assert!(current(false).0.contains_key(&b), "a post"); + save_line(&general, 1, MemberJoined, &a).await; + save_line(&general, 2, MemberLeft, &b).await; + assert!(current(false).1.contains_key(&b), "a presence line"); + crate::db::get_write_connection_guard_static().unwrap() + .execute("UPDATE events SET tags = ?1 WHERE id = 'b1'", ["[[\"unauthorized\"]]"]).unwrap(); + current(false); + current(true); + crate::db::events::delete_event("a1").await.unwrap(); + current(false); + current(true); + } + #[tokio::test] async fn join_lines_turned_off_stay_kept_for_the_member_list() { use crate::stored_event::SystemEventType::{MemberJoined, MemberLeft}; @@ -5539,11 +6102,11 @@ mod tests { content: "the message itself".into(), at: 1_700_000_000_000, mine: true, - preview_metadata: Some(crate::types::SiteMetadata { + preview_metadata: Some(Box::new(crate::types::SiteMetadata { domain: "example.com".into(), og_title: Some("A title".into()), og_description: None, og_image: None, og_url: Some("https://example.com/a".into()), og_type: None, title: None, description: None, favicon: None, - }), + })), attachments: vec![crate::types::Attachment { id: "b2".repeat(32), key: "c3".repeat(32), nonce: "d4".repeat(16), extension: "jpg".into(), name: "passport.jpg".into(), url: "https://blossom.example/x.jpg".into(), size: 42, @@ -5624,8 +6187,7 @@ mod tests { before.4, (vec![(Epoch(0), v2.community_root)], vec![(Epoch(0), [0x62; 32])], vec![("e1".to_string(), 5, r#"{"action":"message_delete"}"#.to_string())]) ); - // File captions are stored but not shown again yet; the view still carries the rest. - assert_eq!(before.5, vec![(String::new(), dm.preview_metadata.clone(), dm.attachments.clone())]); + assert_eq!(before.5, vec![(dm.content.clone(), dm.preview_metadata.clone(), dm.attachments.clone())]); assert_eq!(before.6.as_deref(), Some("still sending")); assert_eq!(before.7, (vec![banned.to_hex()], vec!["d8".repeat(32)], 1, Some(1)), "the banned author stays hidden"); let sealed: (String, String, String) = crate::db::get_db_connection_guard_static().unwrap().query_row( @@ -5902,7 +6464,7 @@ fn held_author_retractions(conn: &rusqlite::Connection, community_id: &str, chan Ok(crate::crypto::open_batch(|o| { rows.into_iter() .filter_map(|(seq, channel, body)| { - let (author, since, generation, until) = author_owed_from_body(&o.open_blob_or_keep(&body))?; + let (author, since, generation, until) = author_owed_from_body(&o.open_blob_owned(body))?; Some(AuthorOwed { seq, channel, author, since, generation, until }) }) .collect() @@ -6077,7 +6639,7 @@ fn read_departures(conn: &rusqlite::Connection, community_id: &str) -> Result)> = crate::crypto::open_batch(|o| { - rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_or_keep(&body)).map(|(member, owed)| (member, (seq, owed)))).collect() + rows.into_iter().filter_map(|(seq, body)| departure_from_body(&o.open_blob_owned(body)).map(|(member, owed)| (member, (seq, owed)))).collect() }); let rows = held.values().map(|(seq, _)| *seq).collect(); Ok(DeparturesSeen { spans: std::sync::Arc::new(held.into_iter().map(|(member, (_, owed))| (member, owed.into())).collect()), rows }) @@ -6322,19 +6884,34 @@ pub fn hold_wrap(community_id: &str, channel_id: &str, wrap_id: &str, wrap: &str /// A stored Control wrap: its id, its own timestamp (seconds), and its body unless it was refused. pub type ControlWrapRow = ([u8; 32], u64, Option>); -/// Every wrap id held for `view`, the refused ones too, each with its timestamp. +struct ControlWrapIdsKey; +type ControlWrapIdsCopy = super::changes::Copy<(String, [u8; 32]), Vec<([u8; 32], u64)>>; + +/// Every wrap id held for `view`, the refused ones too, each with its timestamp; read once +/// a session until a Control wrap is stored. pub fn control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result, String> { + let copy = super::current_session().scoped::(); + copy.get(&super::changes::CONTROL_WRAPS, (community_id.to_string(), *view), || read_control_wrap_ids(community_id, view)) +} + +fn read_control_wrap_ids(community_id: &str, view: &[u8; 32]) -> Result, String> { let conn = super::get_db_connection_guard_static()?; let mut stmt = conn .prepare_cached("SELECT wrap_id, created_at FROM community_control_wraps WHERE community_id = ?1 AND view = ?2") .map_err(|e| format!("control wrap ids: {e}"))?; let rows = stmt - .query_map(params![community_id, &view[..]], |r| Ok((r.get::<_, Vec>(0)?, r.get::<_, i64>(1)?))) + .query_map(params![community_id, &view[..]], |r| { + let id = match r.get_ref(0)?.as_blob() { + Ok(b) => <[u8; 32]>::try_from(b).ok(), + Err(_) => <[u8; 32]>::try_from(r.get::<_, Vec>(0)?).ok(), + }; + Ok((id, r.get::<_, i64>(1)?)) + }) .map_err(|e| format!("control wrap ids: {e}"))?; let mut out = Vec::new(); for row in rows { let (id, at) = row.map_err(|e| format!("control wrap ids: {e}"))?; - out.push((id.try_into().map_err(|_| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64)); + out.push((id.ok_or_else(|| "control wrap ids: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64)); } Ok(out) } @@ -6390,7 +6967,7 @@ pub fn control_wrap_page(community_id: &str, view: &[u8; 32], below: Option<(u64 }; crate::crypto::open_batch(|o| { rows.into_iter() - .map(|(id, at, body)| Ok((id.try_into().map_err(|_| "control wrap page: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64, o.open_blob_or_keep(&body)))) + .map(|(id, at, body)| Ok((id.try_into().map_err(|_| "control wrap page: a wrap id is not 32 bytes".to_string())?, at.max(0) as u64, o.open_blob_owned(body)))) .collect() }) } @@ -6409,11 +6986,19 @@ pub fn control_wrap_bodies(community_id: &str, view: &[u8; 32], ids: &[[u8; 32]] } } } - crate::crypto::open_batch(|o| Ok(sealed.iter().map(|body| o.open_blob_or_keep(body)).collect())) + crate::crypto::open_batch(|o| Ok(sealed.into_iter().map(|body| o.open_blob_owned(body)).collect())) } /// What `view` holds: bodies, refusals, and the bodies' bytes as stored. pub fn control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> { + let copy = super::current_session().scoped::(); + copy.get(&super::changes::CONTROL_WRAPS, (community_id.to_string(), *view), || read_control_wrap_counts(community_id, view)) +} + +struct ControlWrapCountsKey; +type ControlWrapCountsCopy = super::changes::Copy<(String, [u8; 32]), (usize, usize, usize)>; + +fn read_control_wrap_counts(community_id: &str, view: &[u8; 32]) -> Result<(usize, usize, usize), String> { let conn = super::get_db_connection_guard_static()?; conn.query_row( "SELECT COUNT(wrap), COUNT(*) - COUNT(wrap), COALESCE(SUM(length(wrap)), 0) FROM community_control_wraps WHERE community_id = ?1 AND view = ?2", @@ -6671,3 +7256,9 @@ pub fn get_community_pins(community_id: &str, channel_id: &str) -> Result