mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
61
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
709d8c0c67 | ||
|
|
c914d7bee7 | ||
|
|
82ab3509e1 | ||
|
|
f970cb167e | ||
|
|
d15daac302 | ||
|
|
9826c2cde5 | ||
|
|
f73fbfb719 | ||
|
|
b9e5fcfae4 | ||
|
|
9eb0719c3d | ||
|
|
3bb5bdef39 | ||
|
|
7e6e4276d1 | ||
|
|
a566448ae2 | ||
|
|
f28eab0894 | ||
|
|
596191b537 | ||
|
|
6c158c689d | ||
|
|
2e1208470b | ||
|
|
a82c445f5a | ||
|
|
a21a6be4f7 | ||
|
|
ff4d9aaff2 | ||
|
|
666d0abebb | ||
|
|
6a56293d2c | ||
|
|
deab73945b | ||
|
|
280105bd51 | ||
|
|
ce0826aaac | ||
|
|
64392aeae8 | ||
|
|
d9a80b5c94 | ||
|
|
4aa3ba34ea | ||
|
|
c48cb4c7c9 | ||
|
|
17712cd3c8 | ||
|
|
7696c8e7f1 | ||
|
|
89705cd268 | ||
|
|
408a7b2837 | ||
|
|
376f38ec3b | ||
|
|
1fe1016df5 | ||
|
|
e9609c5255 | ||
|
|
ca5df1bed7 | ||
|
|
1f0a776a1a | ||
|
|
7f3ece6eda | ||
|
|
750ae08ffd | ||
|
|
9abf21841a | ||
|
|
b00735b22c | ||
|
|
710a7aff55 | ||
|
|
c7bca0ca4f | ||
|
|
205e570f62 | ||
|
|
c3555ff748 | ||
|
|
2e2dbed7ca | ||
|
|
180b78ce3d | ||
|
|
4e259011c2 | ||
|
|
a2416bf330 | ||
|
|
49b50cca7b | ||
|
|
f94031c7ec | ||
|
|
90df05063f | ||
|
|
bdec449e32 | ||
|
|
f0b94fe6a6 | ||
|
|
c95588ec29 | ||
|
|
c6ac909dda | ||
|
|
0a7544427c | ||
|
|
730861f327 | ||
|
|
0e70f7dd48 | ||
|
|
034b741592 | ||
|
|
5f6753f6d6 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/ca7dd793caba8999ec33fde99bb721a69c3d221f.tar.gz
|
||||
77e8a6b68d67a8d5fcfd6268a6b7938ac9322d877378c6563e933a57df6da821
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/f6a8460b0e85d05bb93a9536dc3d6ed6cc331178.tar.gz
|
||||
6e8ea35b8fe9f7a371c5c2570259c0e0be8a52cbdfa747551874724b0c58a576
|
||||
+2
-4
@@ -4,10 +4,8 @@ rustflags = ["--cfg=web_sys_unstable_apis"]
|
||||
|
||||
[target.'cfg(target_family = "wasm")']
|
||||
rustflags = [
|
||||
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
|
||||
# The current simd implementation leads to undefined behavior
|
||||
#"-C",
|
||||
#"target-feature=+simd128",
|
||||
"-C",
|
||||
"target-feature=+simd128",
|
||||
"-C",
|
||||
"target-feature=+bulk-memory",
|
||||
"-C",
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
},
|
||||
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
"containerEnv": {
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.121",
|
||||
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
|
||||
"CARGO_ABOUT_VERSION": "0.9.2",
|
||||
"BINARYEN_VERSION": "130",
|
||||
"CARGO_BINSTALL_VERSION": "1.23.0"
|
||||
|
||||
+98
-44
@@ -52,29 +52,29 @@ jobs:
|
||||
contents: write
|
||||
deployments: write
|
||||
pull-requests: write
|
||||
actions: write
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache
|
||||
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend and Binaryen
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
BINARYEN_VERSION: "130"
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: 🟢 Install Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -84,14 +84,26 @@ jobs:
|
||||
|
||||
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
|
||||
run: |
|
||||
if ! wasm-bindgen --version 2>/dev/null | grep -qF "$WASM_BINDGEN_CLI_VERSION"; then
|
||||
cargo install -f "wasm-bindgen-cli@$WASM_BINDGEN_CLI_VERSION"
|
||||
# Extracts into a temporary folder first so a cancelled download can't leave a truncated binary that later runs mistake for a finished install
|
||||
install_release_archive() {
|
||||
local url="$1" destination="$2"
|
||||
rm -rf "$destination.partial"
|
||||
mkdir -p "$destination.partial"
|
||||
curl -sSfL "$url" | tar xz -C "$destination.partial" --strip-components=1
|
||||
rm -rf "$destination"
|
||||
mv "$destination.partial" "$destination"
|
||||
}
|
||||
|
||||
# Each version gets its own folder so branches pinning different versions don't keep replacing each other's install
|
||||
WASM_BINDGEN_DIR="$HOME/.cache/wasm-bindgen-$WASM_BINDGEN_CLI_VERSION"
|
||||
if [ ! -x "$WASM_BINDGEN_DIR/wasm-bindgen" ]; then
|
||||
install_release_archive "https://github.com/wasm-bindgen/wasm-bindgen/releases/download/$WASM_BINDGEN_CLI_VERSION/wasm-bindgen-$WASM_BINDGEN_CLI_VERSION-x86_64-unknown-linux-musl.tar.gz" "$WASM_BINDGEN_DIR"
|
||||
fi
|
||||
echo "$WASM_BINDGEN_DIR" >> "$GITHUB_PATH"
|
||||
|
||||
BINARYEN_DIR="$HOME/.cache/binaryen-version_$BINARYEN_VERSION"
|
||||
if [ ! -x "$BINARYEN_DIR/bin/wasm-opt" ]; then
|
||||
mkdir -p "$BINARYEN_DIR"
|
||||
curl -sSfL "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" | tar xz -C "$BINARYEN_DIR" --strip-components=1
|
||||
install_release_archive "https://github.com/WebAssembly/binaryen/releases/download/version_$BINARYEN_VERSION/binaryen-version_$BINARYEN_VERSION-x86_64-linux.tar.gz" "$BINARYEN_DIR"
|
||||
fi
|
||||
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
|
||||
|
||||
@@ -124,6 +136,8 @@ jobs:
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||
@@ -133,7 +147,7 @@ jobs:
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
DEPLOY_BRANCH="master"
|
||||
else
|
||||
DEPLOY_BRANCH="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
|
||||
DEPLOY_BRANCH="$HEAD_BRANCH"
|
||||
if [ "$DEPLOY_BRANCH" = "master" ] || [ -z "$DEPLOY_BRANCH" ]; then
|
||||
DEPLOY_BRANCH="preview-${{ github.run_id }}"
|
||||
fi
|
||||
@@ -165,6 +179,8 @@ jobs:
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
CF_URL: ${{ steps.cloudflare.outputs.url }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CF_URL" ]; then
|
||||
echo "No Cloudflare URL available, skipping deployment."
|
||||
@@ -181,7 +197,7 @@ jobs:
|
||||
AUTO_INACTIVE="true"
|
||||
TRANSIENT_ENVIRONMENT="false"
|
||||
else
|
||||
REF="${{ inputs.checkout_ref || github.head_ref || github.ref_name }}"
|
||||
REF="$HEAD_BRANCH"
|
||||
ENVIRONMENT="graphite-dev (Preview)"
|
||||
AUTO_INACTIVE="false"
|
||||
TRANSIENT_ENVIRONMENT="true"
|
||||
@@ -271,7 +287,7 @@ jobs:
|
||||
|
||||
- name: 📦 Upload web bundle artifact
|
||||
if: github.event_name != 'pull_request' && inputs.merge_queue == false
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-web-bundle
|
||||
path: frontend/dist
|
||||
@@ -283,11 +299,24 @@ jobs:
|
||||
cd frontend
|
||||
npm run check
|
||||
|
||||
# Runs on a GitHub-hosted runner to keep the self-hosted one free for web builds
|
||||
code-docs:
|
||||
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 📃 Trigger website rebuild if auto-generated code docs are stale
|
||||
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
rustup update stable
|
||||
cargo run -p editor-message-tree -- website/generated
|
||||
TREE=volunteer/guide/codebase-overview/hierarchical-message-system-tree
|
||||
curl -sf "https://graphite.art/$TREE.txt" -o "website/static/$TREE.live.txt" \
|
||||
@@ -304,20 +333,20 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -325,8 +354,9 @@ jobs:
|
||||
rustflags: ""
|
||||
target: wasm32-unknown-unknown
|
||||
|
||||
- name: 💾 Set up Cargo cache
|
||||
uses: actions/cache@v5
|
||||
- name: 💾 Restore Cargo cache
|
||||
id: cargo-cache
|
||||
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -335,7 +365,7 @@ jobs:
|
||||
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
|
||||
- name: 🟢 Install Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
@@ -344,7 +374,7 @@ jobs:
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/[email protected]
|
||||
uses: cargo-bins/cargo-binstall@b874e25ea559687bec77e281e9b271aa1367b624 # v1.23.0
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
|
||||
@@ -375,6 +405,17 @@ jobs:
|
||||
CARGO_TERM_COLOR: always
|
||||
run: cargo run build desktop${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 💾 Save Cargo cache
|
||||
# Only master pushes save, since `!build` runs build unmerged PR code yet would save into master's cache scope
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/master' && steps.cargo-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ steps.cargo-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: 📁 Stage artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -385,7 +426,7 @@ jobs:
|
||||
|
||||
- name: 📦 Upload Windows bundle
|
||||
if: github.event_name != 'push'
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-windows-bundle
|
||||
path: target/artifacts
|
||||
@@ -412,7 +453,7 @@ jobs:
|
||||
|
||||
- name: 🔑 Azure login
|
||||
if: github.event_name == 'push'
|
||||
uses: azure/login@v1
|
||||
uses: azure/login@cb79c773a3cfa27f31f25eb3f677781210c9ce3d # v1.6.1
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
@@ -421,7 +462,7 @@ jobs:
|
||||
|
||||
- name: 🔏 Sign
|
||||
if: github.event_name == 'push'
|
||||
uses: azure/artifact-signing-action@v1
|
||||
uses: azure/artifact-signing-action@b443cf8ea4124818d2ea9f043cba29fc3ec47b16 # v1.2.0
|
||||
with:
|
||||
endpoint: https://eus.codesigning.azure.net/
|
||||
signing-account-name: Graphite
|
||||
@@ -432,8 +473,6 @@ jobs:
|
||||
${{ github.workspace }}\target\artifacts\Graphite\chrome_elf.dll
|
||||
${{ github.workspace }}\target\artifacts\Graphite\vulkan-1.dll
|
||||
${{ github.workspace }}\target\artifacts\Graphite\dxcompiler.dll
|
||||
${{ github.workspace }}\target\artifacts\Graphite\libEGL.dll
|
||||
${{ github.workspace }}\target\artifacts\Graphite\libGLESv2.dll
|
||||
${{ github.workspace }}\target\artifacts\Graphite\vk_swiftshader.dll
|
||||
file-digest: SHA256
|
||||
timestamp-rfc3161: http://timestamp.acs.microsoft.com
|
||||
@@ -489,7 +528,7 @@ jobs:
|
||||
|
||||
- name: 📦 Upload signed Windows bundle
|
||||
if: github.event_name == 'push'
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-windows-bundle-signed
|
||||
path: target/artifacts
|
||||
@@ -503,20 +542,20 @@ jobs:
|
||||
|
||||
env:
|
||||
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.127"
|
||||
BINARYEN_VERSION: "130"
|
||||
CARGO_ABOUT_VERSION: "0.9.2"
|
||||
CARGO_BINSTALL_VERSION: "1.23.0"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -524,8 +563,9 @@ jobs:
|
||||
rustflags: ""
|
||||
target: wasm32-unknown-unknown
|
||||
|
||||
- name: 💾 Set up Cargo cache
|
||||
uses: actions/cache@v5
|
||||
- name: 💾 Restore Cargo cache
|
||||
id: cargo-cache
|
||||
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
@@ -534,7 +574,7 @@ jobs:
|
||||
key: cargo-${{ runner.os }}-${{ hashFiles('**/Cargo.lock') }}
|
||||
|
||||
- name: 🟢 Install Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
@@ -543,7 +583,7 @@ jobs:
|
||||
frontend/package-lock.json
|
||||
|
||||
- name: 📦 Install Cargo-binstall
|
||||
uses: cargo-bins/[email protected]
|
||||
uses: cargo-bins/cargo-binstall@b874e25ea559687bec77e281e9b271aa1367b624 # v1.23.0
|
||||
with:
|
||||
version: ${{ env.CARGO_BINSTALL_VERSION }}
|
||||
|
||||
@@ -577,6 +617,17 @@ jobs:
|
||||
CARGO_TERM_COLOR: always
|
||||
run: cargo run build desktop${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 💾 Save Cargo cache
|
||||
# Only master pushes save, since `!build` runs build unmerged PR code yet would save into master's cache scope
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/master' && steps.cargo-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ steps.cargo-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: 📁 Stage artifacts
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -587,7 +638,7 @@ jobs:
|
||||
|
||||
- name: 📦 Upload Mac bundle
|
||||
if: github.event_name != 'push'
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-mac-bundle
|
||||
path: target/artifacts
|
||||
@@ -683,7 +734,7 @@ jobs:
|
||||
|
||||
- name: 📦 Upload signed Mac bundle
|
||||
if: github.event_name == 'push'
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-mac-bundle-signed
|
||||
path: target/artifacts
|
||||
@@ -697,13 +748,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
@@ -716,26 +767,29 @@ jobs:
|
||||
run: nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths --print-build-logs
|
||||
|
||||
- name: 📤 Push to Nix cache
|
||||
# Only master pushes write to the Nix caches, since `!build` runs build unmerged PR code and would otherwise be handed the cache tokens
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && secrets.NIX_CACHE_AUTH_TOKEN || secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
NIX_CACHE_NAME: ${{ (!inputs.debug && github.ref == 'refs/heads/master') && 'graphite' || 'graphite-dev' }}
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN }}
|
||||
NIX_CACHE_NAME: graphite
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build .#graphite${{ inputs.debug && '-dev' || '' }} --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
nix build .#graphite --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
|
||||
- name: 📤 Push Dependencies to dev Nix cache
|
||||
if: github.event_name == 'push' && github.ref == 'refs/heads/master'
|
||||
env:
|
||||
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
|
||||
NIX_CACHE_NAME: graphite-dev
|
||||
run: |
|
||||
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
|
||||
nix build .#graphite${{ inputs.debug && '-dev' || '' }}.deps --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
nix build .#graphite.deps --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
|
||||
|
||||
- name: 🏗 Build Linux bundle
|
||||
run: nix build .#graphite-bundle${{ inputs.debug && '-dev' || '' }}.tar.xz && cp ./result ./graphite-linux-bundle.tar.xz
|
||||
|
||||
- name: 📦 Upload Linux bundle
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-linux-bundle
|
||||
path: graphite-linux-bundle.tar.xz
|
||||
@@ -785,7 +839,7 @@ jobs:
|
||||
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 📦 Upload Flatpak package
|
||||
uses: actions/upload-artifact@v6
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-flatpak
|
||||
path: .flatpak/Graphite.flatpak
|
||||
|
||||
@@ -9,18 +9,20 @@ jobs:
|
||||
cargo-deny:
|
||||
if: github.repository == 'GraphiteEditor/Graphite' # Don't run on forks by default
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 🔒 Check crate security advisories for root workspace
|
||||
uses: EmbarkStudios/cargo-deny-action@v2
|
||||
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
|
||||
with:
|
||||
command: check advisories
|
||||
|
||||
- name: 🔒 Check crate security advisories for /libraries/rawkit
|
||||
uses: EmbarkStudios/cargo-deny-action@v2
|
||||
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
|
||||
with:
|
||||
command: check advisories
|
||||
manifest-path: libraries/rawkit/Cargo.toml
|
||||
+120
-19
@@ -4,48 +4,145 @@ on:
|
||||
pull_request: {}
|
||||
merge_group: {}
|
||||
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (merge queue refs are unique per entry, so those never cancel each other)
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
# Check if CI can be skipped (for merge queue deduplication)
|
||||
# Skip a merge queue run's checks when another Check run already passed them on the exact same content (Git tree)
|
||||
skip-check:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
# Read the trees of the merge queue commit and of the commits other runs tested
|
||||
contents: read
|
||||
# Find the head commit of the PR being merged
|
||||
pull-requests: read
|
||||
# List this workflow's other runs
|
||||
actions: read
|
||||
outputs:
|
||||
skip: ${{ steps.check.outputs.skip-check }}
|
||||
skip: ${{ steps.check.outputs.skip }}
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: 🚦 Check if CI can be skipped
|
||||
id: check
|
||||
uses: cariad-tech/merge-queue-ci-skipper@cf80db21fc70244e36487acc531b3f1118889b0a
|
||||
# A failed or hung step leaves the output unset, which runs the checks
|
||||
continue-on-error: true
|
||||
timeout-minutes: 2
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
MERGE_GROUP_HEAD_REF: ${{ github.event.merge_group.head_ref }}
|
||||
MERGE_GROUP_HEAD_SHA: ${{ github.event.merge_group.head_sha }}
|
||||
run: |
|
||||
if [ "$GITHUB_EVENT_NAME" != "merge_group" ]; then
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
echo "Not a merge queue run, so the checks will run"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Records the decision and shows its reason on the run's summary page
|
||||
decide() {
|
||||
echo "skip=$1" >> "$GITHUB_OUTPUT"
|
||||
echo "::notice::$2"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Prints the tree of a commit, which is the hash of its exact file content
|
||||
tree_of() {
|
||||
local tree
|
||||
tree=$(gh api "$repository_api/git/commits/$1" --jq '.tree.sha') && [[ "$tree" =~ ^[0-9a-f]{40}$ ]] && echo "$tree"
|
||||
}
|
||||
|
||||
repository_api="repos/$GITHUB_REPOSITORY"
|
||||
workflow_path="${GITHUB_WORKFLOW_REF%%@*}"
|
||||
workflow_runs_api="$repository_api/actions/workflows/${workflow_path##*/}/runs"
|
||||
merge_queue_branch="${MERGE_GROUP_HEAD_REF#refs/heads/}"
|
||||
|
||||
merge_group_tree=$(tree_of "$MERGE_GROUP_HEAD_SHA") || decide false "Running the checks since the merge queue commit $MERGE_GROUP_HEAD_SHA couldn't be read"
|
||||
echo "The merge queue commit $MERGE_GROUP_HEAD_SHA has tree $merge_group_tree"
|
||||
|
||||
[[ "$merge_queue_branch" =~ ^gh-readonly-queue/.+/pr-([0-9]+)-[0-9a-f]+$ ]] || decide false "Running the checks since the merge queue branch '$merge_queue_branch' doesn't name a PR"
|
||||
pr_number="${BASH_REMATCH[1]}"
|
||||
pr_head_sha=$(gh api "$repository_api/pulls/$pr_number" --jq '.head.sha') || decide false "Running the checks since PR #$pr_number couldn't be read"
|
||||
|
||||
# The PR's own runs check out the PR merged into its base branch at that moment, which matches this content if the PR was up to date or its base hasn't moved since.
|
||||
# Each run records the commit it loaded the local build.yml from (called by the build job below), and that is the merge commit it checked out.
|
||||
export PR_MERGE_REF="refs/pull/$pr_number/merge"
|
||||
pr_run=$(gh api -X GET "$workflow_runs_api" -f event=pull_request -f head_sha="$pr_head_sha" -f exclude_pull_requests=true -f per_page=100 --jq '
|
||||
[.workflow_runs[] | select(.conclusion != "cancelled")] | max_by(.created_at) // empty
|
||||
| "\(.html_url) \(.conclusion // .status) \([.referenced_workflows[]? | select(.ref == $ENV.PR_MERGE_REF) | .sha] | first // "unknown")"
|
||||
') || decide false "Running the checks since the Check runs of PR #$pr_number couldn't be listed"
|
||||
|
||||
if [ -z "$pr_run" ]; then
|
||||
echo "PR #$pr_number's head commit $pr_head_sha has no Check run that wasn't cancelled"
|
||||
else
|
||||
read -r pr_run_url pr_run_result pr_tested_sha <<< "$pr_run"
|
||||
echo "The newest Check run of PR #$pr_number's head commit $pr_head_sha is $pr_run_url ($pr_run_result), which tested commit $pr_tested_sha"
|
||||
|
||||
if [ "$pr_run_result" != "success" ]; then
|
||||
echo "That run hasn't succeeded"
|
||||
elif ! pr_tested_tree=$(tree_of "$pr_tested_sha"); then
|
||||
echo "The commit that run tested couldn't be read"
|
||||
elif [ "$pr_tested_tree" = "$merge_group_tree" ]; then
|
||||
decide true "Skipping the checks since $pr_run_url already passed on commit $pr_tested_sha, which has this exact content"
|
||||
else
|
||||
echo "That run tested different content (tree $pr_tested_tree)"
|
||||
fi
|
||||
fi
|
||||
|
||||
# A merge queue branch name pairs the PR with the commit it's built on, so an earlier run with this name may have passed on the same content before the PR was queued again
|
||||
earlier_runs=$(gh api -X GET "$workflow_runs_api" -f event=merge_group -f status=success -f branch="$merge_queue_branch" -f exclude_pull_requests=true -f per_page=100 --jq '
|
||||
.workflow_runs[] | select(.id | tostring != $ENV.GITHUB_RUN_ID) | "\(.head_sha) \(.html_url)"
|
||||
') || decide false "Running the checks since the earlier merge queue runs couldn't be listed"
|
||||
|
||||
while read -r earlier_sha earlier_url; do
|
||||
[ -n "$earlier_sha" ] || continue
|
||||
if earlier_tree=$(tree_of "$earlier_sha") && [ "$earlier_tree" = "$merge_group_tree" ]; then
|
||||
decide true "Skipping the checks since $earlier_url already passed on merge queue commit $earlier_sha, which has this exact content"
|
||||
fi
|
||||
done <<< "$earlier_runs"
|
||||
|
||||
decide false "Running the checks since no successful Check run has tested this exact content"
|
||||
|
||||
# Build the web app via the shared build workflow
|
||||
build:
|
||||
needs: skip-check
|
||||
if: needs.skip-check.outputs.skip != 'true'
|
||||
# Always called with the skip decision passed in, since a skipped caller job reports only as `build` and leaves the required `build / web` check missing.
|
||||
# Like the jobs below, the checks still run if `skip-check` itself fails, since a skipped job counts as passing for required checks.
|
||||
if: ${{ !cancelled() }}
|
||||
uses: ./.github/workflows/build.yml
|
||||
# The called workflow's jobs can only narrow these, so this grants the union of what they request
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
deployments: write
|
||||
id-token: write
|
||||
pull-requests: write
|
||||
secrets: inherit
|
||||
with:
|
||||
web: true
|
||||
web: ${{ needs.skip-check.outputs.skip != 'true' }}
|
||||
merge_queue: ${{ github.event_name == 'merge_group' }}
|
||||
|
||||
# Run the Rust tests on the self-hosted native runner
|
||||
test:
|
||||
needs: skip-check
|
||||
if: needs.skip-check.outputs.skip != 'true'
|
||||
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
|
||||
runs-on: [self-hosted, target/native]
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
RUSTC_WRAPPER: /usr/bin/sccache
|
||||
CARGO_INCREMENTAL: 0
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache
|
||||
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend
|
||||
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -64,14 +161,16 @@ jobs:
|
||||
# Rust format check on GitHub runner
|
||||
rust-fmt:
|
||||
needs: skip-check
|
||||
if: needs.skip-check.outputs.skip != 'true'
|
||||
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -85,19 +184,21 @@ jobs:
|
||||
# License compatibility check on GitHub runner
|
||||
check-licenses:
|
||||
needs: skip-check
|
||||
if: needs.skip-check.outputs.skip != 'true'
|
||||
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 📜 Check crate license compatibility for root workspace
|
||||
uses: EmbarkStudios/cargo-deny-action@v2
|
||||
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
|
||||
with:
|
||||
command: check bans licenses sources
|
||||
|
||||
- name: 📜 Check crate license compatibility for /libraries/rawkit
|
||||
uses: EmbarkStudios/cargo-deny-action@v2
|
||||
uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1
|
||||
with:
|
||||
command: check bans licenses sources
|
||||
manifest-path: libraries/rawkit/Cargo.toml
|
||||
@@ -42,9 +42,10 @@ jobs:
|
||||
steps:
|
||||
- name: 🔎 Parse command, find branch, and set build flags
|
||||
id: pr_info
|
||||
env:
|
||||
# Passed through the environment so the comment text can't inject shell syntax
|
||||
COMMENT: ${{ github.event.comment.body }}
|
||||
run: |
|
||||
COMMENT="${{ github.event.comment.body }}"
|
||||
|
||||
# Split into space-separated words
|
||||
read -ra WORDS <<< "$COMMENT"
|
||||
|
||||
@@ -112,19 +113,26 @@ jobs:
|
||||
echo "ref=$(echo $RESPONSE | jq -r '.head.ref')" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: 💬 Edit comment with workflow run link
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
github.rest.issues.updateComment({
|
||||
comment_id: ${{ github.event.comment.id }},
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: '${{ github.event.comment.body }} ([Run ID ' + context.runId + '](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + '))'
|
||||
body: context.payload.comment.body + ' ([Run ID ' + context.runId + '](https://github.com/GraphiteEditor/Graphite/actions/runs/' + context.runId + '))'
|
||||
});
|
||||
|
||||
invoke-build:
|
||||
needs: setup
|
||||
uses: ./.github/workflows/build.yml
|
||||
# The called workflow's jobs can only narrow these, so this grants the union of what they request
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
deployments: write
|
||||
id-token: write
|
||||
pull-requests: write
|
||||
secrets: inherit
|
||||
with:
|
||||
web: ${{ needs.setup.outputs.web == 'true' }}
|
||||
|
||||
@@ -15,10 +15,10 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af # v1.0.7
|
||||
with:
|
||||
profile: minimal
|
||||
toolchain: stable
|
||||
@@ -52,7 +52,7 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: Delete previous comments
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
script: |
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
|
||||
- name: Comment PR
|
||||
if: steps.clippy.outputs.CLIPPY_ISSUES_FOUND == 'true'
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
script: |
|
||||
|
||||
@@ -14,22 +14,25 @@ jobs:
|
||||
profile:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@v1
|
||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||
|
||||
- name: Checkout master branch
|
||||
run: |
|
||||
@@ -51,7 +54,7 @@ jobs:
|
||||
|
||||
- name: Cache benchmark baselines
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v5
|
||||
uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0
|
||||
with:
|
||||
path: target/gungraun
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
@@ -85,7 +88,7 @@ jobs:
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
script: |
|
||||
@@ -111,7 +114,7 @@ jobs:
|
||||
|
||||
- name: Analyze profiling changes
|
||||
id: analyze
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
@@ -177,7 +180,7 @@ jobs:
|
||||
|
||||
- name: Comment PR
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
with:
|
||||
github-token: ${{secrets.GITHUB_TOKEN}}
|
||||
script: |
|
||||
@@ -327,10 +330,12 @@ jobs:
|
||||
|
||||
- name: Fail on significant regressions
|
||||
if: steps.analyze.outputs.has-regressions == 'true'
|
||||
uses: actions/github-script@v8
|
||||
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
|
||||
env:
|
||||
REGRESSION_DETAILS: ${{ steps.analyze.outputs.regression-details }}
|
||||
with:
|
||||
script: |
|
||||
const regressionDetails = JSON.parse('${{ steps.analyze.outputs.regression-details }}');
|
||||
const regressionDetails = JSON.parse(process.env.REGRESSION_DETAILS);
|
||||
const firstRegression = regressionDetails[0];
|
||||
|
||||
core.setFailed(`Significant performance regression detected: ${firstRegression.module_path} ${firstRegression.id} increased by ${firstRegression.absoluteChange.toLocaleString()} instructions (${firstRegression.diffPct.toFixed(2)}%)`);
|
||||
@@ -26,10 +26,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 🦀 Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@166cdcfd11aee3cb47222f9ddb555ce30ddb9659 # v1.17.0
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
rustflags: ""
|
||||
|
||||
- name: 📦 Run sccache-cache
|
||||
uses: mozilla-actions/[email protected]
|
||||
uses: mozilla-actions/sccache-action@9e326ebed976843c9932b3aa0e021c6f50310eb4 # v0.0.6
|
||||
continue-on-error: true
|
||||
|
||||
- name: 🔧 Fallback if sccache fails
|
||||
|
||||
@@ -14,13 +14,13 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
with:
|
||||
repository: ${{ inputs.checkout_repo || github.repository }}
|
||||
ref: ${{ inputs.checkout_ref || '' }}
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
|
||||
@@ -13,10 +13,10 @@ jobs:
|
||||
contents: read
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: ❄ Install Nix
|
||||
uses: DeterminateSystems/nix-installer-action@main
|
||||
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
|
||||
with:
|
||||
extra-conf: |
|
||||
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
|
||||
|
||||
@@ -30,10 +30,10 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@v6
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
|
||||
- name: 🟢 Install Node.js
|
||||
uses: actions/setup-node@v6
|
||||
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version-file: .nvmrc
|
||||
cache: npm
|
||||
@@ -42,12 +42,12 @@ jobs:
|
||||
website/package-lock.json
|
||||
|
||||
- name: 🕸 Install Zola
|
||||
uses: taiki-e/install-action@v2
|
||||
uses: taiki-e/install-action@1e29709c0ec63babbe8f266397a465f29a825f91 # v2.87.31
|
||||
with:
|
||||
tool: [email protected]
|
||||
|
||||
- name: 🔍 Check if `website/other` directory changed
|
||||
uses: dorny/paths-filter@v3
|
||||
uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4
|
||||
id: changes
|
||||
with:
|
||||
filters: |
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ let
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.cargo-about
|
||||
|
||||
pkgs.rustc
|
||||
|
||||
+61
-10
@@ -1,10 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "151.3.24+g2384915+chromium-151.0.7922.174";
|
||||
version = "156.0.8+g426920c+chromium-156.0.8078.48";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-R5ZbnDallYvdbW/bP+M2DzjRfWWRTvY2q63hSIHNxZs=";
|
||||
x86_64-linux = "sha256-21PEP9rOi37krw8AUSARbWlzqp2Ot3AsBhe635voaE4=";
|
||||
aarch64-linux = "sha256-txaNkuJmxyg5zYv5/G1MQ57b19xcEs1+XEw/2IqVSHY=";
|
||||
x86_64-linux = "sha256-3FisWT1Gwh7ixdULjbVzD6zvpCAYOODJ8961k3K/tPo=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
@@ -19,18 +19,67 @@ let
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
|
||||
gl_rpath = pkgs.lib.makeLibraryPath [ pkgs.stdenv.cc.cc ];
|
||||
|
||||
rpath = pkgs.lib.makeLibraryPath [
|
||||
pkgs.glib
|
||||
pkgs.nss
|
||||
pkgs.nspr
|
||||
pkgs.atk
|
||||
pkgs.at-spi2-atk
|
||||
pkgs.libdrm
|
||||
pkgs.expat
|
||||
pkgs.libxkbcommon
|
||||
pkgs.libgbm
|
||||
pkgs.gtk3
|
||||
pkgs.pango
|
||||
pkgs.cairo
|
||||
pkgs.alsa-lib
|
||||
pkgs.dbus
|
||||
pkgs.at-spi2-core
|
||||
pkgs.cups
|
||||
pkgs.libGL
|
||||
pkgs.udev
|
||||
pkgs.systemdLibs
|
||||
pkgs.libxcb
|
||||
pkgs.libx11
|
||||
pkgs.libxcomposite
|
||||
pkgs.libxdamage
|
||||
pkgs.libxext
|
||||
pkgs.libxfixes
|
||||
pkgs.libxrandr
|
||||
pkgs.libxshmfence
|
||||
];
|
||||
in
|
||||
pkgs.stdenv.mkDerivation {
|
||||
pname = "cef-binary";
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
inherit url;
|
||||
hash = selectSystem hashes;
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
|
||||
dontStrip = true;
|
||||
|
||||
dontPatchELF = true;
|
||||
|
||||
installPhase = ''
|
||||
runHook preInstall
|
||||
|
||||
patchelf --set-rpath "${rpath}" --set-interpreter "${pkgs.stdenv.cc.bintools.dynamicLinker}" Release/chrome-sandbox
|
||||
patchelf --add-needed libudev.so --set-rpath "${rpath}" Release/libcef.so
|
||||
if [ -e Release/libEGL.so ]; then
|
||||
patchelf --set-rpath "${gl_rpath}" Release/libEGL.so
|
||||
fi
|
||||
if [ -e Release/libGLESv2.so ]; then
|
||||
patchelf --add-needed libGL.so.1 --set-rpath "${gl_rpath}" Release/libGLESv2.so
|
||||
fi
|
||||
patchelf --set-rpath "${gl_rpath}" Release/libvk_swiftshader.so
|
||||
patchelf --set-rpath "${gl_rpath}" Release/libvulkan.so.1
|
||||
strip ./Release/*.so*
|
||||
mkdir $out/lib
|
||||
|
||||
mkdir -p $out/lib
|
||||
mv ./Release/* $out/lib/
|
||||
find "./Resources/locales" -maxdepth 1 -type f ! -name 'en-US.pak' -delete
|
||||
mv ./Resources/* $out/lib/
|
||||
@@ -45,5 +94,7 @@ pkgs.cef-binary.overrideAttrs {
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/lib/archive.json
|
||||
|
||||
runHook postInstall
|
||||
'';
|
||||
}
|
||||
@@ -84,7 +84,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-bindgen-cli_0_2_127
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
pkgs.importNpmLock.npmConfigHook
|
||||
|
||||
Generated
+563
-2001
File diff suppressed because it is too large.
Load diff
+22
-22
@@ -11,8 +11,6 @@ members = [
|
||||
"document/format",
|
||||
"document/graph-storage",
|
||||
"document/container",
|
||||
"document/peer-transport",
|
||||
"document/live",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -99,16 +97,12 @@ text-nodes = { path = "node-graph/nodes/text" }
|
||||
transform-nodes = { path = "node-graph/nodes/transform" }
|
||||
vector-nodes = { path = "node-graph/nodes/vector" }
|
||||
repeat-nodes = { path = "node-graph/nodes/repeat" }
|
||||
vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
||||
ollev = { git = "https://github.com/tagtraumen/ollev" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
peer-transport = { path = "document/peer-transport" }
|
||||
document-live = { path = "document/live" }
|
||||
raster-nodes = { path = "node-graph/nodes/raster" }
|
||||
graphene-std = { path = "node-graph/nodes/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
@@ -128,7 +122,6 @@ bytemuck = { version = "1.13", features = ["derive", "min_const_generics"] }
|
||||
serde = { version = "1.0", features = ["derive", "rc"] }
|
||||
serde_json = "1.0"
|
||||
postcard = { version = "1.1", default-features = false, features = ["use-std"] }
|
||||
rmp-serde = "1.3"
|
||||
serde_bytes = "0.11"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
reqwest = { version = "0.13", features = ["blocking", "json"] }
|
||||
@@ -150,17 +143,26 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.12"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "29.0", features = [
|
||||
wgpu = { version = "30.0", default-features = false, features = [
|
||||
"std",
|
||||
"parking_lot",
|
||||
"dx12",
|
||||
"metal",
|
||||
"vulkan",
|
||||
"gles",
|
||||
"wgsl",
|
||||
# The web build renders with WebGL2 rather than the less widely supported and less stable WebGPU
|
||||
"webgl",
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
js-sys = "=0.3.104"
|
||||
web-sys = { version = "=0.3.104", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -177,18 +179,14 @@ web-sys = { version = "=0.3.98", features = [
|
||||
"Gpu",
|
||||
"HtmlImageElement",
|
||||
"ImageBitmapRenderingContext",
|
||||
"Lock",
|
||||
"LockManager",
|
||||
"LockOptions",
|
||||
] }
|
||||
winit = "0.31.0-beta.2"
|
||||
winit = "0.31.0-beta.4"
|
||||
keyboard-types = "0.8"
|
||||
url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello = "0.10"
|
||||
vello_encoding = "0.10"
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
usvg = "0.47"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
@@ -240,6 +238,7 @@ syn = { version = "2.0", default-features = false, features = [
|
||||
] }
|
||||
lyon_geom = "1.0"
|
||||
delaunator = "1.0"
|
||||
robust = "1.2"
|
||||
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
@@ -248,8 +247,8 @@ gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "151"
|
||||
cef-dll-sys = "151"
|
||||
cef = "156"
|
||||
cef-dll-sys = "156"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -291,7 +290,8 @@ lto = "thin"
|
||||
debug = true
|
||||
|
||||
[patch.crates-io]
|
||||
winit = { git = "https://github.com/timon-schelling/winit", branch = "graphite" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-151" }
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
|
||||
@@ -18,7 +18,6 @@ accepted = [
|
||||
"NCSA", # Keep this list in sync with those in `/deny.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/deny.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/deny.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/deny.toml`
|
||||
]
|
||||
workarounds = ["ring"]
|
||||
ignore-build-dependencies = true
|
||||
|
||||
@@ -82,7 +82,6 @@ allow = [
|
||||
"NCSA", # Keep this list in sync with those in `/about.toml`
|
||||
"bzip2-1.0.6", # Keep this list in sync with those in `/about.toml`
|
||||
"OFL-1.1", # Keep this list in sync with those in `/about.toml`
|
||||
"Unlicense", # Keep this list in sync with those in `/about.toml`
|
||||
]
|
||||
# The confidence threshold for detecting a license from license text.
|
||||
# The higher the value, the more closely the license text must be to the
|
||||
|
||||
@@ -44,7 +44,6 @@ dirs = { workspace = true }
|
||||
ron = { workspace = true }
|
||||
bytemuck = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
derivative = { workspace = true }
|
||||
rfd = { workspace = true }
|
||||
open = { workspace = true }
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
Name=Graphite
|
||||
GenericName=Vector & Raster Graphics Editor
|
||||
Comment=Open-source vector & raster graphics editor. Featuring node based procedural nondestructive editing workflow.
|
||||
Exec=graphite
|
||||
Exec=graphite %F
|
||||
Terminal=false
|
||||
Type=Application
|
||||
Icon=art.graphite.Graphite
|
||||
Categories=Graphics;VectorGraphics;RasterGraphics;
|
||||
MimeType=application/graphite+json;application/vnd.graphite.document;image/svg+xml;image/png;image/jpeg;image/gif;image/webp;image/bmp;image/tiff;
|
||||
Keywords=graphite;editor;vector;raster;procedural;design;
|
||||
StartupWMClass=art.graphite.Graphite
|
||||
+66
-94
@@ -16,7 +16,6 @@ use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
|
||||
use winit::event_loop::{ActiveEventLoop, AsyncRequestSerial, ControlFlow, DndAction, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use crate::clock::InstantClock;
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
use crate::input::InputState;
|
||||
@@ -24,14 +23,14 @@ use crate::persist;
|
||||
use crate::preferences;
|
||||
use crate::render::{RenderError, RenderState};
|
||||
use crate::spawner::TokioSpawner;
|
||||
use crate::ui::{InputEvent, UiCommand, UiInstance};
|
||||
use crate::ui::{Acceleration, InputEvent, UiCommand, UiConfig, UiInstance};
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction, Preferences};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, Scheduling, WgpuContext, serialize_frontend_messages};
|
||||
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, IngestAction};
|
||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor, serialize_frontend_messages};
|
||||
|
||||
pub(crate) struct App {
|
||||
render_state: Option<RenderState>,
|
||||
wgpu_context: WgpuContext,
|
||||
wgpu_executor: WgpuExecutor,
|
||||
window: Option<Window>,
|
||||
window_scale: f64,
|
||||
window_size: PhysicalSize<u32>,
|
||||
@@ -41,21 +40,18 @@ pub(crate) struct App {
|
||||
pending_dnd_fetch: Option<AsyncRequestSerial>,
|
||||
pending_clipboard_fetch: Option<AsyncRequestSerial>,
|
||||
input_state: InputState,
|
||||
ui_scale: f64,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
desktop_wrapper: DesktopWrapper,
|
||||
ui: UiInstance,
|
||||
ui_frame_received: bool,
|
||||
start_render_sender: SyncSender<()>,
|
||||
web_communication_initialized: bool,
|
||||
ui_initialized: Option<Instant>,
|
||||
web_communication_startup_buffer: Vec<Vec<u8>>,
|
||||
preferences: Preferences,
|
||||
preferences: preferences::DesktopPreferences,
|
||||
launch_documents: Option<Vec<PathBuf>>,
|
||||
startup_time: Option<Instant>,
|
||||
exiting: Arc<AtomicBool>,
|
||||
exit_reason: ExitReason,
|
||||
hide_ui: bool,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -68,7 +64,7 @@ impl App {
|
||||
wgpu_context: WgpuContext,
|
||||
app_event_receiver: Receiver<AppEvent>,
|
||||
app_event_scheduler: AppEventScheduler,
|
||||
preferences: Preferences,
|
||||
preferences: preferences::DesktopPreferences,
|
||||
launch_documents: Vec<PathBuf>,
|
||||
) -> Self {
|
||||
let ctrlc_app_event_scheduler = app_event_scheduler.clone();
|
||||
@@ -98,14 +94,13 @@ impl App {
|
||||
let runtime_wake = move || {
|
||||
let _ = runtime_wake_sender.try_send(());
|
||||
};
|
||||
let wgpu_executor = WgpuExecutor::with_context(wgpu_context).expect("Failed to create WgpuExecutor");
|
||||
let (desktop_wrapper, mut node_runtime) = DesktopWrapper::new(
|
||||
rand::rng().random(),
|
||||
Arc::new(resource_storage),
|
||||
Arc::new(FolderStore::new(dirs::app_autosave_documents_dir())),
|
||||
wgpu_context.clone(),
|
||||
wgpu_executor.clone(),
|
||||
TokioSpawner::new(async_runtime.handle().clone()),
|
||||
Arc::new(InstantClock::new()),
|
||||
Scheduling::default(),
|
||||
editor_wake,
|
||||
runtime_wake,
|
||||
);
|
||||
@@ -116,17 +111,7 @@ impl App {
|
||||
loop {
|
||||
let texture = async_runtime.block_on(node_runtime.run());
|
||||
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
|
||||
// A frame starts after waiting out a deferred one or an idle wait, while a wake mid-frame continues the frame
|
||||
let next_frame = match node_runtime.until_next_frame() {
|
||||
Some(wait) => {
|
||||
thread::sleep(wait);
|
||||
true
|
||||
}
|
||||
None => start_render_receiver.recv_timeout(Duration::from_millis(10)).is_err(),
|
||||
};
|
||||
if next_frame {
|
||||
node_runtime.begin_frame();
|
||||
}
|
||||
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
|
||||
if exiting_clone.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
@@ -135,7 +120,7 @@ impl App {
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
wgpu_context,
|
||||
wgpu_executor,
|
||||
window: None,
|
||||
window_scale: 1.,
|
||||
window_size: PhysicalSize { width: 0, height: 0 },
|
||||
@@ -145,21 +130,18 @@ impl App {
|
||||
pending_dnd_fetch: None,
|
||||
pending_clipboard_fetch: None,
|
||||
input_state: InputState::new(),
|
||||
ui_scale: 1.,
|
||||
app_event_receiver,
|
||||
app_event_scheduler,
|
||||
desktop_wrapper,
|
||||
ui,
|
||||
ui_frame_received: false,
|
||||
start_render_sender,
|
||||
web_communication_initialized: false,
|
||||
ui_initialized: None,
|
||||
web_communication_startup_buffer: Vec::new(),
|
||||
preferences,
|
||||
launch_documents: Some(launch_documents),
|
||||
startup_time: None,
|
||||
exiting,
|
||||
exit_reason: ExitReason::Shutdown,
|
||||
hide_ui: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,11 +161,23 @@ impl App {
|
||||
self.app_event_scheduler.schedule(AppEvent::Exit);
|
||||
}
|
||||
|
||||
fn resize(&mut self) {
|
||||
if self.hide_ui {
|
||||
self.handle_desktop_frontend_message(DesktopFrontendMessage::TmpToggleHideUI, &mut Vec::new());
|
||||
fn restart_ui(&mut self) {
|
||||
let acceleration = self.preferences.acceleration;
|
||||
if let Err(error) = self.ui.restart(UiConfig { acceleration }) {
|
||||
tracing::error!("Failed to restart the UI: {error}");
|
||||
self.exit(Some(ExitReason::Shutdown));
|
||||
return;
|
||||
}
|
||||
self.ui_initialized = None;
|
||||
|
||||
self.window_size = PhysicalSize { width: 0, height: 0 };
|
||||
self.window_scale = 1.;
|
||||
self.window_maximized = false;
|
||||
self.window_fullscreen = false;
|
||||
self.resize();
|
||||
}
|
||||
|
||||
fn resize(&mut self) {
|
||||
let Some(window) = &self.window else {
|
||||
tracing::error!("Resize failed due to missing window");
|
||||
return;
|
||||
@@ -203,7 +197,7 @@ impl App {
|
||||
}
|
||||
|
||||
let size = window.surface_size();
|
||||
let scale = window.scale_factor() * self.ui_scale;
|
||||
let scale = window.scale_factor() * self.preferences.ui_scale;
|
||||
let is_new_size = size != self.window_size;
|
||||
let is_new_scale = scale != self.window_scale;
|
||||
|
||||
@@ -309,19 +303,6 @@ impl App {
|
||||
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
|
||||
|
||||
if self.hide_ui {
|
||||
if x != 0.0 && y != 0.0 {
|
||||
let message = DesktopWrapperMessage::TmpUpdateViewport {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
width: self.window_size.width as f64 / self.window_scale,
|
||||
height: self.window_size.height as f64 / self.window_scale,
|
||||
};
|
||||
self.dispatch_desktop_wrapper_message(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(render_state) = &mut self.render_state
|
||||
&& let Some(window) = &self.window
|
||||
{
|
||||
@@ -339,16 +320,9 @@ impl App {
|
||||
DesktopFrontendMessage::WindowUpdateDirectInput { enabled } => {
|
||||
self.input_state.set_direct_input(enabled);
|
||||
}
|
||||
DesktopFrontendMessage::UpdateUIScale { scale } => {
|
||||
if self.hide_ui {
|
||||
return;
|
||||
}
|
||||
self.ui_scale = scale;
|
||||
self.resize();
|
||||
}
|
||||
DesktopFrontendMessage::UpdateOverlays(scene) => {
|
||||
if let Some(render_state) = &mut self.render_state {
|
||||
render_state.set_overlays_scene(scene);
|
||||
render_state.set_overlays_scene(*scene);
|
||||
}
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
@@ -360,8 +334,26 @@ impl App {
|
||||
DesktopFrontendMessage::PersistenceReadState => {
|
||||
responses.push(DesktopWrapperMessage::LoadPersistedState { state: persist::read_state() });
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceWritePreferences { preferences } => {
|
||||
DesktopFrontendMessage::PersistenceUpdatePreferences { preferences } => {
|
||||
let old_preferences = self.preferences.clone();
|
||||
self.preferences = preferences::DesktopPreferences::from(&preferences);
|
||||
|
||||
preferences::write(preferences);
|
||||
|
||||
if old_preferences.present_mode != self.preferences.present_mode
|
||||
&& let Some(render_state) = &mut self.render_state
|
||||
{
|
||||
render_state.set_present_mode(self.preferences.present_mode);
|
||||
}
|
||||
|
||||
if old_preferences.ui_scale != self.preferences.ui_scale {
|
||||
self.resize();
|
||||
}
|
||||
|
||||
if old_preferences.acceleration != self.preferences.acceleration {
|
||||
tracing::info!("UI acceleration preference changed, restarting UI");
|
||||
self.restart_ui();
|
||||
}
|
||||
}
|
||||
DesktopFrontendMessage::PersistenceLoadPreferences => {
|
||||
let preferences = preferences::read();
|
||||
@@ -370,7 +362,6 @@ impl App {
|
||||
}
|
||||
DesktopFrontendMessage::OpenLaunchDocuments => {
|
||||
let Some(launch_documents) = std::mem::take(&mut self.launch_documents) else {
|
||||
tracing::error!("OpenLaunchDocuments should only be sent once");
|
||||
return;
|
||||
};
|
||||
self.app_event_scheduler.schedule(AppEvent::OpenFiles(launch_documents));
|
||||
@@ -448,22 +439,6 @@ impl App {
|
||||
let message = DesktopWrapperMessage::LoadThirdPartyLicenses { text };
|
||||
responses.push(message);
|
||||
}
|
||||
|
||||
DesktopFrontendMessage::TmpToggleHideUI => {
|
||||
if self.hide_ui {
|
||||
self.hide_ui = false;
|
||||
} else {
|
||||
let message = DesktopWrapperMessage::TmpUpdateViewport {
|
||||
x: 0.,
|
||||
y: 0.,
|
||||
width: self.window_size.width as f64 / self.window_scale,
|
||||
height: self.window_size.height as f64 / self.window_scale,
|
||||
};
|
||||
self.dispatch_desktop_wrapper_message(message);
|
||||
self.render_state.as_mut().unwrap().unbind_ui_texture();
|
||||
self.hide_ui = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,7 +458,7 @@ impl App {
|
||||
}
|
||||
|
||||
fn send_or_queue_web_message(&mut self, message: Vec<u8>) {
|
||||
if self.web_communication_initialized {
|
||||
if self.ui_initialized.is_some() {
|
||||
self.ui.send(UiCommand::Message(message));
|
||||
} else {
|
||||
self.web_communication_startup_buffer.push(message);
|
||||
@@ -493,7 +468,8 @@ impl App {
|
||||
fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) {
|
||||
match event {
|
||||
AppEvent::WebCommunicationInitialized => {
|
||||
self.web_communication_initialized = true;
|
||||
self.ui_initialized = Some(Instant::now());
|
||||
self.ui_frame_received = false;
|
||||
for message in self.web_communication_startup_buffer.drain(..) {
|
||||
self.ui.send(UiCommand::Message(message));
|
||||
}
|
||||
@@ -509,10 +485,6 @@ impl App {
|
||||
}
|
||||
}
|
||||
AppEvent::UiUpdate(texture) => {
|
||||
if self.hide_ui {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(render_state) = self.render_state.as_mut() {
|
||||
render_state.bind_ui_texture(texture);
|
||||
}
|
||||
@@ -558,6 +530,10 @@ impl App {
|
||||
tracing::info!("Exiting main event loop");
|
||||
event_loop.exit();
|
||||
}
|
||||
AppEvent::UiCrashed if self.ui_initialized.is_some() => {
|
||||
tracing::error!("UI process crashed, restarting it.");
|
||||
self.restart_ui();
|
||||
}
|
||||
AppEvent::UiCrashed => {
|
||||
tracing::error!("UI process crashed, exiting.");
|
||||
self.exit(Some(ExitReason::Shutdown));
|
||||
@@ -601,12 +577,10 @@ impl ApplicationHandler for App {
|
||||
let window = Window::new(event_loop, self.app_event_scheduler.clone());
|
||||
self.window = Some(window);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let present_mode = None;
|
||||
#[cfg(target_os = "macos")]
|
||||
let present_mode = if !self.preferences.vsync { Some(wgpu::PresentMode::Immediate) } else { None };
|
||||
|
||||
let render_state = RenderState::new(self.window.as_ref().unwrap(), self.wgpu_context.clone(), present_mode);
|
||||
let mut render_state = RenderState::new(self.window.as_ref().unwrap(), self.wgpu_executor.clone());
|
||||
if self.preferences.present_mode.is_some() {
|
||||
render_state.set_present_mode(self.preferences.present_mode);
|
||||
}
|
||||
self.render_state = Some(render_state);
|
||||
|
||||
if let Some(window) = &self.window.as_ref() {
|
||||
@@ -614,8 +588,6 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
self.resize();
|
||||
|
||||
self.startup_time = Some(Instant::now());
|
||||
}
|
||||
|
||||
fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
|
||||
@@ -678,13 +650,14 @@ impl ApplicationHandler for App {
|
||||
}
|
||||
|
||||
if !self.ui_frame_received
|
||||
&& !self.preferences.disable_ui_acceleration
|
||||
&& self.web_communication_initialized
|
||||
&& let Some(startup_time) = self.startup_time
|
||||
&& startup_time.elapsed() > Duration::from_secs(3)
|
||||
&& self.preferences.acceleration != Acceleration::Disabled
|
||||
&& let Some(initialized) = self.ui_initialized
|
||||
&& initialized.elapsed() > Duration::from_secs(3)
|
||||
{
|
||||
tracing::error!("UI acceleration not working, exiting.");
|
||||
self.exit(Some(ExitReason::UiAccelerationFailure));
|
||||
tracing::error!("UI acceleration not working, disabling it.");
|
||||
let mut preferences = preferences::read();
|
||||
preferences.disable_ui_acceleration = true;
|
||||
self.dispatch_desktop_wrapper_message(DesktopWrapperMessage::LoadPreferences { preferences });
|
||||
}
|
||||
}
|
||||
WindowEvent::DragEntered { id, .. } => {
|
||||
@@ -786,5 +759,4 @@ impl ApplicationHandler for App {
|
||||
pub(crate) enum ExitReason {
|
||||
Shutdown,
|
||||
Restart,
|
||||
UiAccelerationFailure,
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
use crate::wrapper::Clock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// The desktop's monotonic clock, measuring time since the app started it.
|
||||
pub(crate) struct InstantClock(Instant);
|
||||
|
||||
impl InstantClock {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
impl Clock for InstantClock {
|
||||
fn now(&self) -> Duration {
|
||||
self.0.elapsed()
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
use crate::wrapper::{WgpuContext, WgpuContextBuilder, WgpuFeatures};
|
||||
|
||||
pub(super) async fn create_wgpu_context() -> WgpuContext {
|
||||
let mut wgpu_context_builder = WgpuContextBuilder::new().with_features(WgpuFeatures::IMMEDIATES);
|
||||
let mut wgpu_context_builder = WgpuContextBuilder::new()
|
||||
.with_features(WgpuFeatures::IMMEDIATES)
|
||||
.with_optional_features(WgpuFeatures::VULKAN_EXTERNAL_MEMORY_DMA_BUF);
|
||||
|
||||
// TODO: make this configurable via cli flags instead
|
||||
if let Some(index) = std::env::var("GRAPHITE_WGPU_ADAPTER").ok().and_then(|s| s.parse().ok()) {
|
||||
|
||||
+36
-42
@@ -339,57 +339,51 @@ impl ViewportInfo {
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickTracker {
|
||||
left: ClickChains,
|
||||
right: ClickChains,
|
||||
middle: ClickChains,
|
||||
back: ClickChains,
|
||||
forward: ClickChains,
|
||||
latest_press: Option<Press>,
|
||||
}
|
||||
|
||||
struct Press {
|
||||
button: MouseButton,
|
||||
time: Instant,
|
||||
position: (i32, i32),
|
||||
count: u32,
|
||||
dragged: bool,
|
||||
}
|
||||
|
||||
impl ClickTracker {
|
||||
fn input(&mut self, position: PhysicalPosition<f64>, button: MouseButton, state: ElementState) -> u32 {
|
||||
let position = (position.x as i32, position.y as i32);
|
||||
let clicks = match button {
|
||||
MouseButton::Left => &mut self.left,
|
||||
MouseButton::Right => &mut self.right,
|
||||
MouseButton::Middle => &mut self.middle,
|
||||
MouseButton::Back => &mut self.back,
|
||||
MouseButton::Forward => &mut self.forward,
|
||||
_ => return 1,
|
||||
};
|
||||
let chain = match state {
|
||||
ElementState::Pressed => &mut clicks.down,
|
||||
ElementState::Released => &mut clicks.up,
|
||||
};
|
||||
|
||||
let now = Instant::now();
|
||||
let count = match chain {
|
||||
Some(previous) => {
|
||||
let within_time = now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT;
|
||||
let dx = position.0.abs_diff(previous.position.0) as usize;
|
||||
let dy = position.1.abs_diff(previous.position.1) as usize;
|
||||
let within_distance = dx <= MULTICLICK_ALLOWED_TRAVEL && dy <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
if within_time && within_distance { previous.count.saturating_add(1) } else { 1 }
|
||||
let position = (position.x as i32, position.y as i32);
|
||||
let within_travel = |from: (i32, i32)| from.0.abs_diff(position.0) as usize <= MULTICLICK_ALLOWED_TRAVEL && from.1.abs_diff(position.1) as usize <= MULTICLICK_ALLOWED_TRAVEL;
|
||||
|
||||
match state {
|
||||
ElementState::Pressed => {
|
||||
let count = match &self.latest_press {
|
||||
Some(previous) if previous.button == button && !previous.dragged && now.saturating_duration_since(previous.time) <= MULTICLICK_TIMEOUT && within_travel(previous.position) => {
|
||||
previous.count.saturating_add(1)
|
||||
}
|
||||
_ => 1,
|
||||
};
|
||||
self.latest_press = Some(Press {
|
||||
button,
|
||||
time: now,
|
||||
position,
|
||||
count,
|
||||
dragged: false,
|
||||
});
|
||||
count
|
||||
}
|
||||
None => 1,
|
||||
};
|
||||
*chain = Some(Click { time: now, position, count });
|
||||
count
|
||||
ElementState::Released => {
|
||||
let Some(press) = self.latest_press.as_mut().filter(|press| press.button == button) else {
|
||||
return 1;
|
||||
};
|
||||
press.dragged |= !within_travel(press.position);
|
||||
if press.dragged { 1 } else { press.count }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ClickChains {
|
||||
down: Option<Click>,
|
||||
up: Option<Click>,
|
||||
}
|
||||
|
||||
struct Click {
|
||||
time: Instant,
|
||||
position: (i32, i32),
|
||||
count: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ShakeTracker {
|
||||
samples: VecDeque<(PhysicalPosition<f64>, Duration)>,
|
||||
|
||||
+17
-27
@@ -14,7 +14,6 @@ pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||
|
||||
mod app;
|
||||
mod cli;
|
||||
mod clock;
|
||||
mod dirs;
|
||||
mod event;
|
||||
mod gpu_context;
|
||||
@@ -78,8 +77,6 @@ pub fn start() -> ExitCode {
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
let mut prefs = preferences::read();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
|
||||
@@ -91,15 +88,19 @@ pub fn start() -> ExitCode {
|
||||
|
||||
let _socket_handle = socket::start(app_event_scheduler.clone());
|
||||
|
||||
let mut prefs = preferences::DesktopPreferences::from(&preferences::read());
|
||||
|
||||
if cli.disable_ui_acceleration {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
prefs.acceleration = Acceleration::Disabled;
|
||||
preferences::modify(|prefs| {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
});
|
||||
}
|
||||
if prefs.disable_ui_acceleration {
|
||||
if prefs.acceleration == Acceleration::Disabled {
|
||||
println!("UI acceleration is disabled");
|
||||
}
|
||||
|
||||
let acceleration = if prefs.disable_ui_acceleration { Acceleration::Disabled } else { Acceleration::Auto };
|
||||
let ui_context = match ui_context.start(UiConfig { acceleration }) {
|
||||
let ui_context = match ui_context.start(UiConfig { acceleration: prefs.acceleration }) {
|
||||
Ok(context) => context,
|
||||
Err(error) => {
|
||||
tracing::error!("Failed to start the UI runtime: {error}");
|
||||
@@ -149,29 +150,18 @@ pub fn start() -> ExitCode {
|
||||
// ui needs to be shutdown before restarting
|
||||
ui.shutdown();
|
||||
|
||||
// If exiting due to a UI acceleration failure, update preferences to disable it for next launch
|
||||
if matches!(exit_reason, app::ExitReason::UiAccelerationFailure) {
|
||||
tracing::error!("Disabling UI acceleration");
|
||||
preferences::modify(|prefs| {
|
||||
prefs.disable_ui_acceleration = true;
|
||||
});
|
||||
}
|
||||
|
||||
// Explicitly drop the instance lock
|
||||
drop(lock);
|
||||
|
||||
match exit_reason {
|
||||
app::ExitReason::Restart | app::ExitReason::UiAccelerationFailure => {
|
||||
tracing::info!("Restarting application");
|
||||
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
|
||||
#[cfg(target_family = "unix")]
|
||||
let _ = std::os::unix::process::CommandExt::exec(&mut command);
|
||||
#[cfg(target_family = "unix")]
|
||||
tracing::error!("Failed to restart application");
|
||||
#[cfg(not(target_family = "unix"))]
|
||||
let _ = command.spawn();
|
||||
}
|
||||
_ => {}
|
||||
if matches!(exit_reason, app::ExitReason::Restart) {
|
||||
tracing::info!("Restarting application");
|
||||
let mut command = std::process::Command::new(std::env::current_exe().unwrap());
|
||||
#[cfg(target_family = "unix")]
|
||||
let _ = std::os::unix::process::CommandExt::exec(&mut command);
|
||||
#[cfg(target_family = "unix")]
|
||||
tracing::error!("Failed to restart application");
|
||||
#[cfg(not(target_family = "unix"))]
|
||||
let _ = command.spawn();
|
||||
}
|
||||
|
||||
ExitCode::SUCCESS
|
||||
|
||||
@@ -1,4 +1,31 @@
|
||||
use graphite_desktop_wrapper::messages::Preferences;
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::ui::Acceleration;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub(crate) struct DesktopPreferences {
|
||||
pub(crate) acceleration: Acceleration,
|
||||
pub(crate) present_mode: Option<PresentMode>,
|
||||
pub(crate) ui_scale: f64,
|
||||
}
|
||||
|
||||
impl From<&Preferences> for DesktopPreferences {
|
||||
fn from(preferences: &Preferences) -> Self {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let present_mode = None;
|
||||
#[cfg(target_os = "macos")]
|
||||
let present_mode = if !preferences.vsync { Some(PresentMode::Immediate) } else { None };
|
||||
|
||||
let acceleration = if preferences.disable_ui_acceleration { Acceleration::Disabled } else { Acceleration::Auto };
|
||||
|
||||
Self {
|
||||
acceleration,
|
||||
present_mode,
|
||||
ui_scale: preferences.ui_scale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write(preferences: Preferences) {
|
||||
let Ok(preferences) = ron::ser::to_string_pretty(&preferences, Default::default()) else {
|
||||
|
||||
+21
-17
@@ -1,7 +1,7 @@
|
||||
use wgpu::PresentMode;
|
||||
|
||||
use crate::window::Window;
|
||||
use crate::wrapper::{Texture, WgpuContext, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
use crate::wrapper::{Texture, VelloCanvas, VelloSceneBuilder, WgpuCurrentSurfaceTexture, WgpuExecutor, WgpuSurface};
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug)]
|
||||
@@ -21,12 +21,15 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<vello::Scene>,
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
}
|
||||
|
||||
impl RenderState {
|
||||
pub(crate) fn new(window: &Window, context: WgpuContext, present_mode: Option<PresentMode>) -> Self {
|
||||
pub(crate) fn new(window: &Window, executor: WgpuExecutor) -> Self {
|
||||
let context = executor.context();
|
||||
let size = window.surface_size();
|
||||
let surface = window.create_surface(&context.instance);
|
||||
|
||||
@@ -36,9 +39,10 @@ impl RenderState {
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format: surface_format,
|
||||
color_space: wgpu::SurfaceColorSpace::Auto,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
present_mode: present_mode.unwrap_or(surface_caps.present_modes[0]),
|
||||
present_mode: surface_caps.present_modes[0],
|
||||
alpha_mode: surface_caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 1,
|
||||
@@ -161,8 +165,6 @@ impl RenderState {
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let executor = WgpuExecutor::with_context(context).expect("Failed to create WgpuExecutor");
|
||||
|
||||
Self {
|
||||
surface,
|
||||
executor,
|
||||
@@ -179,6 +181,7 @@ impl RenderState {
|
||||
ui_texture: None,
|
||||
bind_group: None,
|
||||
overlays_scene: None,
|
||||
overlays_canvas: VelloCanvas::default(),
|
||||
surface_outdated: true,
|
||||
}
|
||||
}
|
||||
@@ -207,11 +210,6 @@ impl RenderState {
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
pub(crate) fn unbind_ui_texture(&mut self) {
|
||||
self.ui_texture = None;
|
||||
self.update_bindgroup();
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport_scale(&mut self, scale: [f32; 2]) {
|
||||
self.surface_outdated = true;
|
||||
self.viewport_scale = scale;
|
||||
@@ -222,18 +220,24 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: vello::Scene) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
fn render_overlays(&mut self, scene: vello::Scene) {
|
||||
let Some(viewport_texture) = self.viewport_texture.as_ref() else {
|
||||
pub(crate) fn set_present_mode(&mut self, present_mode: Option<PresentMode>) {
|
||||
let context = self.executor.context();
|
||||
self.config.present_mode = present_mode.unwrap_or(self.surface.get_capabilities(&context.adapter).present_modes[0]);
|
||||
self.surface.configure(&context.device, &self.config);
|
||||
self.surface_outdated = true;
|
||||
}
|
||||
|
||||
fn render_overlays(&mut self, scene: VelloSceneBuilder) {
|
||||
if self.viewport_texture.is_none() {
|
||||
tracing::warn!("No viewport texture bound, cannot render overlays");
|
||||
return;
|
||||
};
|
||||
let size = glam::UVec2::new(viewport_texture.width(), viewport_texture.height());
|
||||
let result = self.executor.render_vello_scene(&scene, size, &Default::default(), None);
|
||||
}
|
||||
let result = self.executor.render_vello_scene_on_canvas(&mut self.overlays_canvas, scene);
|
||||
match result {
|
||||
Ok(texture) => {
|
||||
self.overlays_texture = Some(texture);
|
||||
|
||||
@@ -56,4 +56,8 @@ impl BrowserDelegate {
|
||||
pub(crate) fn receive_web_message(&self, message: &[u8]) {
|
||||
self.send(EventMessage::WebMessage(message.to_vec()));
|
||||
}
|
||||
|
||||
pub(crate) fn render_process_terminated(&self) {
|
||||
self.send(EventMessage::RenderProcessTerminated);
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,6 @@ impl EventQueue {
|
||||
let _ = self.sender.send(event);
|
||||
}
|
||||
|
||||
pub(crate) fn terminate(&self, event: UiEvent) {
|
||||
let _ = self.sender.send(event);
|
||||
self.terminated.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub(crate) fn mark_terminated(&self) {
|
||||
self.terminated.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use cef::sys::cef_color_type_t;
|
||||
|
||||
use super::resample::Resampler;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) mod d3d11;
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -7,7 +9,7 @@ pub(crate) mod dmabuf;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) mod iosurface;
|
||||
|
||||
pub(crate) type TextureImportResult = Result<wgpu::Texture, TextureImportError>;
|
||||
pub(crate) type TextureImportResult = Result<ImportedTexture, TextureImportError>;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum TextureImportError {
|
||||
@@ -18,9 +20,6 @@ pub(crate) enum TextureImportError {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
#[error("Hardware acceleration not available: {reason}")]
|
||||
HardwareUnavailable { reason: String },
|
||||
#[error("Vulkan operation failed: {operation}")]
|
||||
#[cfg(target_os = "linux")]
|
||||
VulkanError { operation: String },
|
||||
#[error("Platform-specific error: {message}")]
|
||||
PlatformError { message: String },
|
||||
}
|
||||
@@ -91,6 +90,115 @@ pub(crate) trait TextureImporter {
|
||||
fn import_to_wgpu(&self, device: &wgpu::Device) -> TextureImportResult;
|
||||
}
|
||||
|
||||
pub(crate) struct ImportedTexture {
|
||||
texture: wgpu::Texture,
|
||||
ownership: Option<OwnershipTransfer>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
struct OwnershipTransfer {
|
||||
acquire: wgpu::CommandBuffer,
|
||||
release: wgpu::CommandBuffer,
|
||||
state: wgpu::TextureUses,
|
||||
}
|
||||
|
||||
impl From<wgpu::Texture> for ImportedTexture {
|
||||
fn from(texture: wgpu::Texture) -> Self {
|
||||
Self { texture, ownership: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl ImportedTexture {
|
||||
pub(super) fn copy(self, device: &wgpu::Device, queue: &wgpu_sync::Queue, resampler: &Resampler, content_rect: ContentRect) -> wgpu::Texture {
|
||||
let imported = self.texture;
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("CEF Frame Copy Encoder"),
|
||||
});
|
||||
let output = match content_rect.mapping(imported.width(), imported.height()) {
|
||||
ContentMapping::Identity => {
|
||||
let output = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("CEF Imported Frame Copy"),
|
||||
size: imported.size(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: imported.format(),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &imported,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &output,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
imported.size(),
|
||||
);
|
||||
output
|
||||
}
|
||||
ContentMapping::Scaled(content_rect) => {
|
||||
let output = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("CEF Imported Scaled Frame Copy"),
|
||||
size: wgpu::Extent3d {
|
||||
width: content_rect.source_width,
|
||||
height: content_rect.source_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: imported.format(),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
let size = wgpu::Extent3d {
|
||||
width: content_rect.width,
|
||||
height: content_rect.height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
resampler.encode(
|
||||
&mut encoder,
|
||||
&imported,
|
||||
wgpu::Origin3d {
|
||||
x: content_rect.x,
|
||||
y: content_rect.y,
|
||||
z: 0,
|
||||
},
|
||||
size,
|
||||
&output,
|
||||
);
|
||||
output
|
||||
}
|
||||
};
|
||||
|
||||
match self.ownership {
|
||||
Some(OwnershipTransfer { acquire, release, state }) => {
|
||||
encoder.transition_resources(
|
||||
std::iter::empty(),
|
||||
std::iter::once(wgpu::TextureTransition {
|
||||
texture: &imported,
|
||||
selector: None,
|
||||
state,
|
||||
}),
|
||||
);
|
||||
queue.submit([acquire, encoder.finish(), release]);
|
||||
}
|
||||
None => {
|
||||
queue.submit([encoder.finish()]);
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
fn wgpu_format(format: cef_color_type_t) -> Result<wgpu::TextureFormat, TextureImportError> {
|
||||
match format {
|
||||
cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(wgpu::TextureFormat::Bgra8Unorm),
|
||||
|
||||
@@ -67,9 +67,15 @@ impl D3D11Importer {
|
||||
Ok::<_, TextureImportError>(hal_texture)
|
||||
}?;
|
||||
|
||||
let texture = unsafe { device.create_texture_from_hal::<api::Dx12>(hal_texture, &texture_descriptor(self.width, self.height, self.format, "CEF D3D11→D3D12 Shared Texture")?) };
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<api::Dx12>(
|
||||
hal_texture,
|
||||
&texture_descriptor(self.width, self.height, self.format, "CEF D3D11 -> D3D12 Shared Texture")?,
|
||||
wgpu::TextureUses::UNINITIALIZED,
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
Ok(texture.into())
|
||||
}
|
||||
|
||||
fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
@@ -108,9 +114,15 @@ impl D3D11Importer {
|
||||
Ok::<_, TextureImportError>(hal_texture)
|
||||
}?;
|
||||
|
||||
let texture = unsafe { device.create_texture_from_hal::<Vulkan>(hal_texture, &texture_descriptor(self.width, self.height, self.format, "CEF D3D11 Shared Texture")?) };
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<Vulkan>(
|
||||
hal_texture,
|
||||
&texture_descriptor(self.width, self.height, self.format, "CEF D3D11 Shared Texture")?,
|
||||
wgpu::TextureUses::UNINITIALIZED,
|
||||
)
|
||||
};
|
||||
|
||||
Ok(texture)
|
||||
Ok(texture.into())
|
||||
}
|
||||
|
||||
fn import_d3d11_handle_to_d3d12(&self, hal_device: &<wgpu::hal::api::Dx12 as wgpu::hal::Api>::Device) -> Result<windows::Win32::Graphics::Direct3D12::ID3D12Resource, TextureImportError> {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::{TextureImportError, TextureImportResult, TextureImporter, texture_descriptor, wgpu_format};
|
||||
use super::{ImportedTexture, OwnershipTransfer, TextureImportError, TextureImportResult, TextureImporter, texture_descriptor, wgpu_format};
|
||||
use ash::vk;
|
||||
use cef::sys::cef_color_type_t;
|
||||
use wgpu::hal::api;
|
||||
use wgpu::TextureUses;
|
||||
use wgpu::hal::api::Vulkan;
|
||||
|
||||
pub struct DmaBufImporter {
|
||||
fds: Vec<std::os::fd::OwnedFd>,
|
||||
@@ -28,9 +29,63 @@ impl TextureImporter for DmaBufImporter {
|
||||
)));
|
||||
}
|
||||
|
||||
let texture = self.import_via_vulkan(device)?;
|
||||
let max_dimension = device.limits().max_texture_dimension_2d;
|
||||
if self.width == 0 || self.height == 0 || self.width > max_dimension || self.height > max_dimension {
|
||||
return Err(TextureImportError::InvalidHandle(format!(
|
||||
"Invalid DMA-BUF dimensions {}x{} for the device limit of {max_dimension}",
|
||||
self.width, self.height
|
||||
)));
|
||||
}
|
||||
|
||||
if !device.features().contains(wgpu::Features::VULKAN_EXTERNAL_MEMORY_DMA_BUF) {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device does not support VULKAN_EXTERNAL_MEMORY_DMA_BUF".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let fd = self.fds[0].try_clone().map_err(|e| TextureImportError::PlatformError {
|
||||
message: format!("Failed to duplicate DMA-BUF file descriptor: {e}"),
|
||||
})?;
|
||||
|
||||
let hal_texture = unsafe {
|
||||
let Some(hal_device) = device.as_hal::<Vulkan>() else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Vulkan backend".to_string(),
|
||||
});
|
||||
};
|
||||
hal_device.texture_from_dmabuf_fd(
|
||||
fd,
|
||||
&wgpu::hal::TextureDescriptor {
|
||||
label: Some("CEF DMA-BUF Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu_format(self.format)?,
|
||||
usage: TextureUses::COPY_SRC | TextureUses::RESOURCE,
|
||||
memory_flags: wgpu::hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
},
|
||||
self.modifier,
|
||||
u64::from(self.strides[0]),
|
||||
u64::from(self.offsets[0]),
|
||||
)?
|
||||
};
|
||||
|
||||
let texture = unsafe {
|
||||
device.create_texture_from_hal::<Vulkan>(
|
||||
hal_texture,
|
||||
&texture_descriptor(self.width, self.height, self.format, "CEF DMA-BUF Texture")?,
|
||||
TextureUses::COPY_SRC | TextureUses::RESOURCE,
|
||||
)
|
||||
};
|
||||
let ownership = ownership_transfer(device, &texture)?;
|
||||
tracing::trace!("Successfully imported DMA-BUF texture via Vulkan");
|
||||
Ok(texture)
|
||||
Ok(ImportedTexture { texture, ownership: Some(ownership) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,181 +101,81 @@ impl DmaBufImporter {
|
||||
offsets,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_via_vulkan(&self, device: &wgpu::Device) -> TextureImportResult {
|
||||
use wgpu::{TextureUses, wgc::api::Vulkan};
|
||||
let hal_texture = unsafe {
|
||||
let hal_device_guard = device.as_hal::<api::Vulkan>();
|
||||
let Some(hal_device) = hal_device_guard else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Vulkan backend".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
let (vk_image, device_memory) = self.create_vulkan_image_from_dmabuf(&hal_device)?;
|
||||
|
||||
let hal_texture = <api::Vulkan as wgpu::hal::Api>::Device::texture_from_raw(
|
||||
&hal_device,
|
||||
vk_image,
|
||||
&wgpu::hal::TextureDescriptor {
|
||||
label: Some("CEF DMA-BUF Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu_format(self.format)?,
|
||||
usage: TextureUses::COPY_DST | TextureUses::COPY_SRC | TextureUses::RESOURCE,
|
||||
memory_flags: wgpu::hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
},
|
||||
None,
|
||||
wgpu::hal::vulkan::TextureMemory::Dedicated(device_memory),
|
||||
);
|
||||
|
||||
Ok::<_, TextureImportError>(hal_texture)
|
||||
}?;
|
||||
|
||||
let texture = unsafe { device.create_texture_from_hal::<Vulkan>(hal_texture, &texture_descriptor(self.width, self.height, self.format, "CEF DMA-BUF Texture")?) };
|
||||
|
||||
Ok(texture)
|
||||
}
|
||||
|
||||
fn create_vulkan_image_from_dmabuf(&self, hal_device: &<api::Vulkan as wgpu::hal::Api>::Device) -> Result<(vk::Image, vk::DeviceMemory), TextureImportError> {
|
||||
let device = hal_device.raw_device();
|
||||
let instance = hal_device.shared_instance().raw_instance();
|
||||
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return Err(TextureImportError::InvalidHandle("Invalid DMA-BUF dimensions".to_string()));
|
||||
}
|
||||
|
||||
let image_create_info = vk::ImageCreateInfo::default()
|
||||
.image_type(vk::ImageType::TYPE_2D)
|
||||
.format(vulkan_format(self.format)?)
|
||||
.extent(vk::Extent3D {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
depth: 1,
|
||||
})
|
||||
.mip_levels(1)
|
||||
.array_layers(1)
|
||||
.samples(vk::SampleCountFlags::TYPE_1)
|
||||
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
|
||||
.usage(vk::ImageUsageFlags::SAMPLED | vk::ImageUsageFlags::COLOR_ATTACHMENT | vk::ImageUsageFlags::TRANSFER_SRC)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE);
|
||||
|
||||
let plane_layouts = self
|
||||
.offsets
|
||||
.iter()
|
||||
.zip(&self.strides)
|
||||
.map(|(&offset, &stride)| vk::SubresourceLayout {
|
||||
offset: offset as u64,
|
||||
size: 0, // Will be calculated by driver
|
||||
row_pitch: stride as u64,
|
||||
array_pitch: 0,
|
||||
depth_pitch: 0,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut drm_format_modifier = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default()
|
||||
.drm_format_modifier(self.modifier)
|
||||
.plane_layouts(&plane_layouts);
|
||||
|
||||
let mut external_memory_info = vk::ExternalMemoryImageCreateInfo::default().handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
|
||||
|
||||
let image_create_info = image_create_info.push_next(&mut drm_format_modifier).push_next(&mut external_memory_info);
|
||||
|
||||
let image = unsafe {
|
||||
device.create_image(&image_create_info, None).map_err(|e| TextureImportError::VulkanError {
|
||||
operation: format!("Failed to create Vulkan image: {e:?}"),
|
||||
})?
|
||||
};
|
||||
|
||||
let memory_requirements = unsafe { device.get_image_memory_requirements(image) };
|
||||
|
||||
// Duplicate the file descriptor
|
||||
let dup_fd = unsafe { libc::dup(std::os::fd::AsRawFd::as_raw_fd(&self.fds[0])) };
|
||||
if dup_fd == -1 {
|
||||
// SAFETY: the image was created above and never bound or returned.
|
||||
unsafe { device.destroy_image(image, None) };
|
||||
return Err(TextureImportError::PlatformError {
|
||||
message: "Failed to duplicate DMA-BUF file descriptor".to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
let external_memory_fd = ash::khr::external_memory_fd::Device::new(instance, device);
|
||||
let mut fd_properties = vk::MemoryFdPropertiesKHR::default();
|
||||
if let Err(e) = unsafe { external_memory_fd.get_memory_fd_properties(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, dup_fd, &mut fd_properties) } {
|
||||
// SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd
|
||||
unsafe {
|
||||
device.destroy_image(image, None);
|
||||
libc::close(dup_fd);
|
||||
}
|
||||
return Err(TextureImportError::VulkanError {
|
||||
operation: format!("Failed to query DMA-BUF fd memory properties: {e:?}"),
|
||||
});
|
||||
}
|
||||
|
||||
let mut import_memory_fd = vk::ImportMemoryFdInfoKHR::default().handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT).fd(dup_fd);
|
||||
|
||||
let memory_properties = unsafe { instance.get_physical_device_memory_properties(hal_device.raw_physical_device()) };
|
||||
|
||||
let compatible_type_bits = memory_requirements.memory_type_bits & fd_properties.memory_type_bits;
|
||||
let Some(memory_type_index) = find_memory_type_index(compatible_type_bits, vk::MemoryPropertyFlags::empty(), &memory_properties) else {
|
||||
// SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd
|
||||
unsafe {
|
||||
device.destroy_image(image, None);
|
||||
libc::close(dup_fd);
|
||||
}
|
||||
return Err(TextureImportError::VulkanError {
|
||||
operation: "Failed to find suitable memory type for DMA-BUF".to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
let allocate_info = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(memory_requirements.size)
|
||||
.memory_type_index(memory_type_index)
|
||||
.push_next(&mut import_memory_fd);
|
||||
|
||||
let device_memory = match unsafe { device.allocate_memory(&allocate_info, None) } {
|
||||
Ok(memory) => memory,
|
||||
Err(e) => {
|
||||
// SAFETY: import failed and the fd is still ours, need to clean up the image and close the fd
|
||||
unsafe {
|
||||
device.destroy_image(image, None);
|
||||
libc::close(dup_fd);
|
||||
}
|
||||
return Err(TextureImportError::VulkanError {
|
||||
operation: format!("Failed to allocate memory for DMA-BUF: {e:?}"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(e) = unsafe { device.bind_image_memory(image, device_memory, 0) } {
|
||||
// SAFETY: import failed, need to clean up the image and free the memory
|
||||
unsafe {
|
||||
device.destroy_image(image, None);
|
||||
device.free_memory(device_memory, None);
|
||||
}
|
||||
return Err(TextureImportError::VulkanError {
|
||||
operation: format!("Failed to bind memory to image: {e:?}"),
|
||||
});
|
||||
}
|
||||
|
||||
Ok((image, device_memory))
|
||||
}
|
||||
}
|
||||
|
||||
fn vulkan_format(format: cef_color_type_t) -> Result<vk::Format, TextureImportError> {
|
||||
match format {
|
||||
cef_color_type_t::CEF_COLOR_TYPE_BGRA_8888 => Ok(vk::Format::B8G8R8A8_UNORM),
|
||||
cef_color_type_t::CEF_COLOR_TYPE_RGBA_8888 => Ok(vk::Format::R8G8B8A8_UNORM),
|
||||
_ => Err(TextureImportError::UnsupportedFormat { format }),
|
||||
}
|
||||
fn ownership_transfer(device: &wgpu::Device, texture: &wgpu::Texture) -> Result<OwnershipTransfer, TextureImportError> {
|
||||
let (raw_device, local_queue_family, external_queue_family, image) = unsafe {
|
||||
let (Some(hal_device), Some(hal_texture)) = (device.as_hal::<Vulkan>(), texture.as_hal::<Vulkan>()) else {
|
||||
return Err(TextureImportError::HardwareUnavailable {
|
||||
reason: "Device is not using Vulkan backend".to_string(),
|
||||
});
|
||||
};
|
||||
let external_queue_family = if hal_device.enabled_device_extensions().contains(&ash::ext::queue_family_foreign::NAME) {
|
||||
vk::QUEUE_FAMILY_FOREIGN_EXT
|
||||
} else {
|
||||
vk::QUEUE_FAMILY_EXTERNAL
|
||||
};
|
||||
(hal_device.raw_device().clone(), hal_device.queue_family_index(), external_queue_family, hal_texture.raw_handle())
|
||||
};
|
||||
|
||||
let barrier = vk::ImageMemoryBarrier::default()
|
||||
.image(image)
|
||||
.subresource_range(vk::ImageSubresourceRange {
|
||||
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||
base_mip_level: 0,
|
||||
level_count: 1,
|
||||
base_array_layer: 0,
|
||||
layer_count: 1,
|
||||
})
|
||||
.old_layout(vk::ImageLayout::GENERAL)
|
||||
.new_layout(vk::ImageLayout::GENERAL);
|
||||
|
||||
let acquire = record_barrier(
|
||||
device,
|
||||
&raw_device,
|
||||
barrier
|
||||
.src_queue_family_index(external_queue_family)
|
||||
.dst_queue_family_index(local_queue_family)
|
||||
.dst_access_mask(vk::AccessFlags::MEMORY_READ),
|
||||
vk::PipelineStageFlags::TOP_OF_PIPE,
|
||||
vk::PipelineStageFlags::ALL_COMMANDS,
|
||||
)?;
|
||||
let release = record_barrier(
|
||||
device,
|
||||
&raw_device,
|
||||
barrier
|
||||
.src_queue_family_index(local_queue_family)
|
||||
.dst_queue_family_index(external_queue_family)
|
||||
.src_access_mask(vk::AccessFlags::MEMORY_READ),
|
||||
vk::PipelineStageFlags::ALL_COMMANDS,
|
||||
vk::PipelineStageFlags::BOTTOM_OF_PIPE,
|
||||
)?;
|
||||
|
||||
Ok(OwnershipTransfer {
|
||||
acquire,
|
||||
release,
|
||||
state: TextureUses::COPY_SRC | TextureUses::RESOURCE,
|
||||
})
|
||||
}
|
||||
|
||||
fn find_memory_type_index(type_filter: u32, properties: vk::MemoryPropertyFlags, mem_properties: &vk::PhysicalDeviceMemoryProperties) -> Option<u32> {
|
||||
(0..mem_properties.memory_type_count).find(|&i| (type_filter & (1 << i)) != 0 && mem_properties.memory_types[i as usize].property_flags.contains(properties))
|
||||
fn record_barrier(
|
||||
device: &wgpu::Device,
|
||||
raw_device: &ash::Device,
|
||||
barrier: vk::ImageMemoryBarrier<'_>,
|
||||
src_stage: vk::PipelineStageFlags,
|
||||
dst_stage: vk::PipelineStageFlags,
|
||||
) -> Result<wgpu::CommandBuffer, TextureImportError> {
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("CEF DMA-BUF Ownership Transfer"),
|
||||
});
|
||||
unsafe {
|
||||
encoder.as_hal_mut::<Vulkan, _, _>(|hal_encoder| {
|
||||
let hal_encoder = hal_encoder.ok_or_else(|| TextureImportError::HardwareUnavailable {
|
||||
reason: "Command encoder is not using Vulkan backend".to_string(),
|
||||
})?;
|
||||
raw_device.cmd_pipeline_barrier(hal_encoder.raw_handle(), src_stage, dst_stage, vk::DependencyFlags::empty(), &[], &[], &[barrier]);
|
||||
Ok::<_, TextureImportError>(())
|
||||
})?;
|
||||
}
|
||||
Ok(encoder.finish())
|
||||
}
|
||||
@@ -81,6 +81,7 @@ impl IOSurfaceImporter {
|
||||
height: texture_desc.size.height,
|
||||
depth: texture_desc.array_layer_count(),
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
Ok::<_, TextureImportError>(hal_tex)
|
||||
@@ -88,6 +89,6 @@ impl IOSurfaceImporter {
|
||||
texture
|
||||
};
|
||||
|
||||
Ok(unsafe { device.create_texture_from_hal::<wgpu::wgc::api::Metal>(hal_tex, &texture_desc) })
|
||||
Ok(unsafe { device.create_texture_from_hal::<wgpu::wgc::api::Metal>(hal_tex, &texture_desc, wgpu::TextureUses::UNINITIALIZED) }.into())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
use super::import::ContentMapping;
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
use super::resample::Resampler;
|
||||
|
||||
@@ -33,7 +31,7 @@ impl FrameSurface {
|
||||
return None;
|
||||
};
|
||||
|
||||
if buffer.chunks_exact(4).take(width as usize).all(|pixel| pixel[3] == 0) {
|
||||
if buffer.as_chunks::<4>().0.iter().take(width as usize).all(|pixel| pixel[3] == 0) {
|
||||
tracing::debug!("Skipping fully transparent frame");
|
||||
return None;
|
||||
}
|
||||
@@ -81,93 +79,15 @@ impl FrameSurface {
|
||||
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
pub(crate) fn import_texture(&self, importer: impl crate::frames::import::TextureImporter, content_rect: crate::frames::import::ContentRect) -> Option<wgpu::Texture> {
|
||||
let imported = match importer.import_to_wgpu(&self.device) {
|
||||
Ok(texture) => texture,
|
||||
let output = match importer.import_to_wgpu(&self.device) {
|
||||
Ok(imported) => imported.copy(&self.device, &self.queue, &self.resampler, content_rect),
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to import remote accelerated frame: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("CEF Frame Copy Encoder"),
|
||||
});
|
||||
let output = match content_rect.mapping(imported.width(), imported.height()) {
|
||||
ContentMapping::Identity => {
|
||||
let output = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("CEF Imported Frame Copy"),
|
||||
size: imported.size(),
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: imported.format(),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
encoder.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &imported,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &output,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
imported.size(),
|
||||
);
|
||||
output
|
||||
}
|
||||
ContentMapping::Scaled(content_rect) => {
|
||||
let output = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("CEF Imported Scaled Frame Copy"),
|
||||
size: wgpu::Extent3d {
|
||||
width: content_rect.source_width,
|
||||
height: content_rect.source_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: imported.format(),
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
});
|
||||
let size = wgpu::Extent3d {
|
||||
width: content_rect.width,
|
||||
height: content_rect.height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
self.resampler.encode(
|
||||
&mut encoder,
|
||||
&imported,
|
||||
wgpu::Origin3d {
|
||||
x: content_rect.x,
|
||||
y: content_rect.y,
|
||||
z: 0,
|
||||
},
|
||||
size,
|
||||
&output,
|
||||
);
|
||||
output
|
||||
}
|
||||
};
|
||||
|
||||
let blank_check = blank_check::encode_readback(&self.device, &mut encoder, &output);
|
||||
|
||||
let submission = self.queue.submit([encoder.finish()]);
|
||||
|
||||
let blank_check = blank_check.map();
|
||||
|
||||
let _ = self.device.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(submission),
|
||||
timeout: None,
|
||||
});
|
||||
|
||||
if blank_check.check_is_blank() {
|
||||
if blank_check::is_blank(&self.device, &self.queue, &output) {
|
||||
tracing::debug!("Skipping fully transparent accelerated frame");
|
||||
return None;
|
||||
}
|
||||
@@ -188,7 +108,7 @@ mod blank_check {
|
||||
const STRIP_BYTES: u32 = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||
const STRIP_TEXELS: u32 = STRIP_BYTES / 4;
|
||||
|
||||
pub(super) fn encode_readback(device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> PendingBlankCheck {
|
||||
pub(super) fn is_blank(device: &wgpu::Device, queue: &wgpu_sync::Queue, texture: &wgpu::Texture) -> bool {
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("CEF Blank Check"),
|
||||
size: STRIP_BYTES as u64,
|
||||
@@ -196,6 +116,9 @@ mod blank_check {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let width = texture.width().min(STRIP_TEXELS);
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("CEF Blank Check Encoder"),
|
||||
});
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture,
|
||||
@@ -221,43 +144,18 @@ mod blank_check {
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
PendingBlankCheck { buffer, width }
|
||||
}
|
||||
let submission = queue.submit([encoder.finish()]);
|
||||
|
||||
pub(super) struct PendingBlankCheck {
|
||||
buffer: wgpu::Buffer,
|
||||
width: u32,
|
||||
}
|
||||
let slice = buffer.slice(..u64::from(width) * 4);
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
let _ = device.poll(wgpu::PollType::Wait {
|
||||
submission_index: Some(submission),
|
||||
timeout: None,
|
||||
});
|
||||
|
||||
impl PendingBlankCheck {
|
||||
pub(super) fn map(self) -> MappedBlankCheck {
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
self.buffer.slice(..u64::from(self.width) * 4).map_async(wgpu::MapMode::Read, move |result| {
|
||||
let _ = sender.send(result);
|
||||
});
|
||||
MappedBlankCheck {
|
||||
buffer: self.buffer,
|
||||
width: self.width,
|
||||
receiver,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct MappedBlankCheck {
|
||||
buffer: wgpu::Buffer,
|
||||
width: u32,
|
||||
receiver: mpsc::Receiver<Result<(), wgpu::BufferAsyncError>>,
|
||||
}
|
||||
|
||||
impl MappedBlankCheck {
|
||||
pub(super) fn check_is_blank(self) -> bool {
|
||||
match self.receiver.try_recv() {
|
||||
Ok(Ok(())) => {
|
||||
let slice = self.buffer.slice(..u64::from(self.width) * 4);
|
||||
slice.get_mapped_range().chunks_exact(4).all(|texel| texel[3] == 0)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
matches!(receiver.try_recv(), Ok(Ok(()))) && slice.get_mapped_range().is_ok_and(|view| view.as_chunks::<4>().0.iter().all(|texel| texel[3] == 0))
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ impl BrowserProcessClientImpl {
|
||||
load_handler: LoadHandler::new(LoadHandlerImpl::new(delegate.clone())),
|
||||
render_handler: RenderHandler::new(RenderHandlerImpl::new(delegate.clone(), frames)),
|
||||
display_handler: DisplayHandler::new(DisplayHandlerImpl::new(delegate.clone())),
|
||||
request_handler: RequestHandler::new(RequestHandlerImpl::new()),
|
||||
request_handler: RequestHandler::new(RequestHandlerImpl::new(delegate.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,23 @@
|
||||
use cef::rc::{Rc, RcImpl};
|
||||
use cef::sys::{_cef_request_handler_t, cef_base_ref_counted_t};
|
||||
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, WrapRequestHandler};
|
||||
use cef::{AuthCallback, Browser, CefString, Frame, ImplRequest, ImplRequestHandler, Request, ResourceRequestHandler, TerminationStatus, WrapRequestHandler};
|
||||
use std::ffi::c_int;
|
||||
|
||||
use super::resource_request_handler::ResourceRequestHandlerImpl;
|
||||
use crate::consts::{RESOURCE_DOMAIN, RESOURCE_SCHEME};
|
||||
use crate::delegate::BrowserDelegate;
|
||||
|
||||
pub(crate) struct RequestHandlerImpl {
|
||||
object: *mut RcImpl<_cef_request_handler_t, Self>,
|
||||
delegate: BrowserDelegate,
|
||||
}
|
||||
|
||||
impl RequestHandlerImpl {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self { object: std::ptr::null_mut() }
|
||||
pub(crate) fn new(delegate: BrowserDelegate) -> Self {
|
||||
Self {
|
||||
object: std::ptr::null_mut(),
|
||||
delegate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +60,11 @@ impl ImplRequestHandler for RequestHandlerImpl {
|
||||
0
|
||||
}
|
||||
|
||||
fn on_render_process_terminated(&self, _browser: Option<&mut Browser>, status: TerminationStatus, error_code: c_int, _error_string: Option<&CefString>) {
|
||||
tracing::error!("CEF render process terminated: {status:?} ({error_code})");
|
||||
self.delegate.render_process_terminated();
|
||||
}
|
||||
|
||||
fn get_raw(&self) -> *mut _cef_request_handler_t {
|
||||
self.object.cast()
|
||||
}
|
||||
@@ -66,7 +76,10 @@ impl Clone for RequestHandlerImpl {
|
||||
let rc_impl = &mut *self.object;
|
||||
rc_impl.interface.add_ref();
|
||||
}
|
||||
Self { object: self.object }
|
||||
Self {
|
||||
object: self.object,
|
||||
delegate: self.delegate.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Rc for RequestHandlerImpl {
|
||||
|
||||
+28
-15
@@ -1,7 +1,7 @@
|
||||
use std::process::ExitCode;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, RecvTimeoutError};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::remote::messages::HostControlMessage;
|
||||
@@ -47,7 +47,7 @@ impl UiContext<Setup> {
|
||||
}
|
||||
|
||||
pub fn start(self, config: UiConfig) -> Result<UiContext<Started>, UiError> {
|
||||
let acceleration = platform::accelerated_paint(matches!(config.acceleration, Acceleration::Disabled));
|
||||
let acceleration = platform::accelerated_paint(config.acceleration);
|
||||
let handle = remote::spawn::spawn_host(acceleration)?;
|
||||
Ok(UiContext { inner: Arc::new(handle) })
|
||||
}
|
||||
@@ -65,14 +65,14 @@ impl UiContext<Started> {
|
||||
let surface = frames::FrameSurface::new(device.clone(), queue.clone());
|
||||
|
||||
let (queue, events) = events::EventQueue::new();
|
||||
let shutdown_complete = remote::spawn::start_instance(&self.inner, surface, queue.clone())?;
|
||||
remote::spawn::start_instance(&self.inner, surface.clone(), queue.clone())?;
|
||||
|
||||
Ok(UiInstance {
|
||||
inner: Arc::new(UiInstanceInner {
|
||||
host: self.inner.clone(),
|
||||
host: Mutex::new(self.inner.clone()),
|
||||
surface,
|
||||
events: Mutex::new(events),
|
||||
queue,
|
||||
shutdown_complete: Mutex::new(shutdown_complete),
|
||||
shutdown_started: AtomicBool::new(false),
|
||||
}),
|
||||
})
|
||||
@@ -142,22 +142,24 @@ pub struct UiInstance {
|
||||
}
|
||||
|
||||
pub(crate) struct UiInstanceInner {
|
||||
host: Arc<HostHandle>,
|
||||
host: Mutex<Arc<HostHandle>>,
|
||||
surface: frames::FrameSurface,
|
||||
events: Mutex<Receiver<UiEvent>>,
|
||||
queue: events::EventQueue,
|
||||
shutdown_complete: Mutex<Receiver<()>>,
|
||||
shutdown_started: AtomicBool,
|
||||
}
|
||||
|
||||
impl UiInstance {
|
||||
pub fn send(&self, command: UiCommand) {
|
||||
let shared = &self.inner;
|
||||
let Ok(host) = self.inner.host.lock() else {
|
||||
return;
|
||||
};
|
||||
match command {
|
||||
UiCommand::Input(event) => shared.host.send(HostControlMessage::Input(event)),
|
||||
UiCommand::Resized { width, height } => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
|
||||
UiCommand::ScaleChanged(scale) => shared.host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
|
||||
UiCommand::Refresh => shared.host.send(HostControlMessage::RefreshViewInfo),
|
||||
UiCommand::Message(message) => shared.host.send(HostControlMessage::SendWebMessage(message)),
|
||||
UiCommand::Input(event) => host.send(HostControlMessage::Input(event)),
|
||||
UiCommand::Resized { width, height } => host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Size { width, height })),
|
||||
UiCommand::ScaleChanged(scale) => host.send(HostControlMessage::UpdateViewInfo(view::ViewInfoUpdate::Scale(scale))),
|
||||
UiCommand::Refresh => host.send(HostControlMessage::RefreshViewInfo),
|
||||
UiCommand::Message(message) => host.send(HostControlMessage::SendWebMessage(message)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,6 +181,17 @@ impl UiInstance {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restart(&self, config: UiConfig) -> Result<(), UiError> {
|
||||
let shared = &self.inner;
|
||||
let mut host = shared.host.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
host.shutdown();
|
||||
|
||||
let restarted = remote::spawn::spawn_host(platform::accelerated_paint(config.acceleration))?;
|
||||
remote::spawn::start_instance(&restarted, shared.surface.clone(), shared.queue.clone())?;
|
||||
*host = Arc::new(restarted);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
self.inner.shutdown();
|
||||
}
|
||||
@@ -195,8 +208,8 @@ impl UiInstanceInner {
|
||||
if self.shutdown_started.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
if let Ok(receiver) = self.shutdown_complete.lock() {
|
||||
self.host.shutdown(&receiver);
|
||||
if let Ok(host) = self.host.lock() {
|
||||
host.shutdown();
|
||||
}
|
||||
self.queue.mark_terminated();
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use crate::Acceleration;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -5,14 +7,14 @@ pub(crate) mod mac;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) mod win;
|
||||
|
||||
pub(crate) fn accelerated_paint(disable_gpu_acceleration: bool) -> bool {
|
||||
pub(crate) fn accelerated_paint(acceleration: Acceleration) -> bool {
|
||||
#[cfg(feature = "accelerated_paint")]
|
||||
{
|
||||
!disable_gpu_acceleration && should_enable_hardware_acceleration()
|
||||
acceleration == Acceleration::Auto && should_enable_hardware_acceleration()
|
||||
}
|
||||
#[cfg(not(feature = "accelerated_paint"))]
|
||||
{
|
||||
let _ = disable_gpu_acceleration;
|
||||
let _ = acceleration;
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,12 +81,7 @@ pub(crate) fn run() {
|
||||
let outcome = context.run(move |handle| control_loop(&control_receiver, &handle, sequence.as_ref()));
|
||||
|
||||
match outcome {
|
||||
ControlOutcome::Shutdown => {
|
||||
tracing::debug!("Shut down CEF host");
|
||||
if let Ok(sender) = event_sender.lock() {
|
||||
let _ = sender.send(EventMessage::ShutdownComplete);
|
||||
}
|
||||
}
|
||||
ControlOutcome::Shutdown => tracing::debug!("Shut down CEF host"),
|
||||
ControlOutcome::Disconnected => std::process::exit(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,5 +47,5 @@ pub(crate) enum EventMessage {
|
||||
format: u32,
|
||||
content: Option<crate::frames::import::ContentRect>,
|
||||
},
|
||||
ShutdownComplete,
|
||||
RenderProcessTerminated,
|
||||
}
|
||||
@@ -42,17 +42,10 @@ impl HostHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn shutdown(&self, shutdown_complete_receiver: &mpsc::Receiver<()>) {
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutting_down.store(true, Ordering::SeqCst);
|
||||
let deadline = Instant::now() + HOST_SHUTDOWN_TIMEOUT;
|
||||
|
||||
if self.sender.send(HostControlMessage::Shutdown).is_ok() {
|
||||
match shutdown_complete_receiver.recv_timeout(HOST_SHUTDOWN_TIMEOUT) {
|
||||
Ok(()) => tracing::debug!("CEF host completed shutdown"),
|
||||
Err(RecvTimeoutError::Timeout) => tracing::warn!("Timed out waiting for the CEF host to shut down"),
|
||||
Err(RecvTimeoutError::Disconnected) => tracing::debug!("CEF host connection closed during shutdown"),
|
||||
}
|
||||
}
|
||||
let _ = self.sender.send(HostControlMessage::Shutdown);
|
||||
|
||||
loop {
|
||||
match self.child.lock() {
|
||||
@@ -233,7 +226,7 @@ pub(crate) fn spawn_host(acceleration: bool) -> Result<HostHandle, UiError> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events: EventQueue) -> Result<mpsc::Receiver<()>, UiError> {
|
||||
pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events: EventQueue) -> Result<(), UiError> {
|
||||
let receive_side = match handle.receivers.lock() {
|
||||
Ok(mut receive_side) => receive_side.take(),
|
||||
Err(_) => None,
|
||||
@@ -242,7 +235,6 @@ pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events:
|
||||
return Err(UiError::InstanceLimit);
|
||||
};
|
||||
|
||||
let (shutdown_complete_sender, shutdown_complete_receiver) = mpsc::channel();
|
||||
let consumer = FrameConsumer::new(surface, events.clone(), handle.sender.clone());
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "macos"), feature = "accelerated_paint"))]
|
||||
@@ -263,7 +255,7 @@ pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events:
|
||||
let events = events.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("cef-host".to_string())
|
||||
.spawn(move || event_receiver_loop(receiver, consumer, events, shutting_down, died_reported, shutdown_complete_sender))
|
||||
.spawn(move || event_receiver_loop(receiver, consumer, events, shutting_down, died_reported))
|
||||
.map_err(|e| UiError::Bootstrap(format!("failed to spawn the host event receiver thread: {e}")))?;
|
||||
}
|
||||
|
||||
@@ -286,7 +278,7 @@ pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events:
|
||||
if shutting_down.load(Ordering::SeqCst) {
|
||||
tracing::debug!("CEF host exited during shutdown: {status}");
|
||||
} else {
|
||||
report_host_died(&died_reported, &events, &format!("CEF host process exited unexpectedly: {status}"));
|
||||
report_crash(&died_reported, &events, &format!("CEF host process exited unexpectedly: {status}"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -297,25 +289,18 @@ pub(crate) fn start_instance(handle: &HostHandle, surface: FrameSurface, events:
|
||||
.map_err(|e| UiError::Bootstrap(format!("failed to spawn the host supervisor thread: {e}")))?;
|
||||
}
|
||||
|
||||
Ok(shutdown_complete_receiver)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report_host_died(died_reported: &AtomicBool, events: &EventQueue, message: &str) {
|
||||
fn report_crash(died_reported: &AtomicBool, events: &EventQueue, message: &str) {
|
||||
if died_reported.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
tracing::error!("{message}");
|
||||
events.terminate(UiEvent::Crashed);
|
||||
events.send(UiEvent::Crashed);
|
||||
}
|
||||
|
||||
fn event_receiver_loop(
|
||||
receiver: IpcReceiver<EventMessage>,
|
||||
consumer: FrameConsumer,
|
||||
events: EventQueue,
|
||||
shutting_down: Arc<AtomicBool>,
|
||||
died_reported: Arc<AtomicBool>,
|
||||
shutdown_complete_sender: mpsc::Sender<()>,
|
||||
) {
|
||||
fn event_receiver_loop(receiver: IpcReceiver<EventMessage>, consumer: FrameConsumer, events: EventQueue, shutting_down: Arc<AtomicBool>, died_reported: Arc<AtomicBool>) {
|
||||
let mut newest_frame: Option<PendingFrame> = None;
|
||||
let mut segments = SegmentTable::new();
|
||||
|
||||
@@ -325,21 +310,21 @@ fn event_receiver_loop(
|
||||
Err(ipc_channel::IpcError::Io(ref io)) if io.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => {
|
||||
if !shutting_down.load(Ordering::SeqCst) {
|
||||
report_host_died(&died_reported, &events, &format!("Lost connection to the CEF host process: {e:?}"));
|
||||
report_crash(&died_reported, &events, &format!("Lost connection to the CEF host process: {e:?}"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
handle_message(message, &events, &shutting_down, &died_reported, &shutdown_complete_sender, &mut newest_frame, &mut segments);
|
||||
handle_message(message, &events, &shutting_down, &died_reported, &mut newest_frame, &mut segments);
|
||||
|
||||
loop {
|
||||
match receiver.try_recv() {
|
||||
Ok(message) => handle_message(message, &events, &shutting_down, &died_reported, &shutdown_complete_sender, &mut newest_frame, &mut segments),
|
||||
Ok(message) => handle_message(message, &events, &shutting_down, &died_reported, &mut newest_frame, &mut segments),
|
||||
Err(ipc_channel::TryRecvError::Empty) => break,
|
||||
Err(ipc_channel::TryRecvError::IpcError(ipc_channel::IpcError::Io(ref io))) if io.kind() == std::io::ErrorKind::Interrupted => break,
|
||||
Err(ipc_channel::TryRecvError::IpcError(e)) => {
|
||||
if !shutting_down.load(Ordering::SeqCst) {
|
||||
report_host_died(&died_reported, &events, &format!("Lost connection to the CEF host process: {e:?}"));
|
||||
report_crash(&died_reported, &events, &format!("Lost connection to the CEF host process: {e:?}"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -352,22 +337,14 @@ fn event_receiver_loop(
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_message(
|
||||
message: EventMessage,
|
||||
events: &EventQueue,
|
||||
shutting_down: &AtomicBool,
|
||||
died_reported: &AtomicBool,
|
||||
shutdown_complete_sender: &mpsc::Sender<()>,
|
||||
newest_frame: &mut Option<PendingFrame>,
|
||||
segments: &mut SegmentTable,
|
||||
) {
|
||||
fn handle_message(message: EventMessage, events: &EventQueue, shutting_down: &AtomicBool, died_reported: &AtomicBool, newest_frame: &mut Option<PendingFrame>, segments: &mut SegmentTable) {
|
||||
match message {
|
||||
EventMessage::Hello { .. } => tracing::error!("Unexpected second Hello from the CEF host"),
|
||||
EventMessage::BrowserCreated => tracing::info!("CEF host created the browser"),
|
||||
EventMessage::InitFailed(e) => {
|
||||
tracing::error!("CEF initialization failed in the host process: {e}");
|
||||
died_reported.store(true, Ordering::SeqCst);
|
||||
events.terminate(UiEvent::Failure(e.to_string()));
|
||||
events.send(UiEvent::Failure(e.to_string()));
|
||||
}
|
||||
EventMessage::WebCommunicationInitialized => events.send(UiEvent::Ready),
|
||||
EventMessage::WebMessage(message) => events.send(UiEvent::Message(message)),
|
||||
@@ -393,9 +370,10 @@ fn handle_message(
|
||||
*newest_frame = Some(frame);
|
||||
}
|
||||
}
|
||||
EventMessage::ShutdownComplete => {
|
||||
shutting_down.store(true, Ordering::SeqCst);
|
||||
let _ = shutdown_complete_sender.send(());
|
||||
EventMessage::RenderProcessTerminated => {
|
||||
if !shutting_down.load(Ordering::SeqCst) {
|
||||
report_crash(died_reported, events, "CEF render process terminated unexpectedly");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -77,10 +77,5 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text: text };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
|
||||
DesktopWrapperMessage::TmpUpdateViewport { x, y, width, height } => {
|
||||
let message = ViewportMessage::TmpUpdateBounds { x, y, width, height };
|
||||
dispatcher.queue_editor_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use super::messages::{DesktopFrontendMessage, IngestAction, SaveFileDialogContex
|
||||
pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: FrontendMessage) -> Option<FrontendMessage> {
|
||||
match message {
|
||||
FrontendMessage::RenderOverlays { context } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene()));
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateOverlays(context.take_scene().into()));
|
||||
}
|
||||
FrontendMessage::TriggerBrowse { options, action } => {
|
||||
let title = match action {
|
||||
@@ -59,10 +59,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height });
|
||||
}
|
||||
FrontendMessage::UpdateUIScale { scale } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::UpdateUIScale { scale });
|
||||
return Some(FrontendMessage::UpdateUIScale { scale });
|
||||
}
|
||||
FrontendMessage::TriggerPersistenceReadState => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceReadState);
|
||||
}
|
||||
@@ -72,8 +68,8 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerOpenLaunchDocuments => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenLaunchDocuments);
|
||||
}
|
||||
FrontendMessage::TriggerSavePreferences { preferences } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceWritePreferences { preferences });
|
||||
FrontendMessage::TriggerUpdatePreferences { preferences } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceUpdatePreferences { preferences });
|
||||
}
|
||||
FrontendMessage::TriggerLoadPreferences => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PersistenceLoadPreferences);
|
||||
@@ -103,12 +99,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerClipboardWrite { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite { content });
|
||||
}
|
||||
// The desktop app has no web origin to build the link from, so it points at the hosted editor.
|
||||
FrontendMessage::TriggerSessionLinkCopy { token } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::ClipboardWrite {
|
||||
content: format!("https://editor.graphite.rs/?session={token}"),
|
||||
});
|
||||
}
|
||||
FrontendMessage::WindowPointerLock => {
|
||||
dispatcher.respond(DesktopFrontendMessage::PointerLock);
|
||||
}
|
||||
@@ -148,10 +138,6 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
FrontendMessage::TriggerDisplayThirdPartyLicensesDialog => {
|
||||
dispatcher.respond(DesktopFrontendMessage::LoadThirdPartyLicenses);
|
||||
}
|
||||
|
||||
FrontendMessage::TmpToggleHideUI => {
|
||||
dispatcher.respond(DesktopFrontendMessage::TmpToggleHideUI);
|
||||
}
|
||||
m => return Some(m),
|
||||
}
|
||||
None
|
||||
|
||||
@@ -12,8 +12,10 @@ use std::sync::Arc;
|
||||
pub use graph_craft::application_io::resource::MmapResourceStorage;
|
||||
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
|
||||
pub use graphite_editor::document_store::{DocumentStore, FolderStore};
|
||||
pub use graphite_editor::task::{Clock, Scheduling, Spawn, Task};
|
||||
pub use graphite_editor::task::{Spawn, Task};
|
||||
pub use wgpu_executor::Texture;
|
||||
pub use wgpu_executor::VelloCanvas;
|
||||
pub use wgpu_executor::VelloSceneBuilder;
|
||||
pub use wgpu_executor::WgpuBackends;
|
||||
pub use wgpu_executor::WgpuContext;
|
||||
pub use wgpu_executor::WgpuContextBuilder;
|
||||
@@ -35,15 +37,12 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
document_store: Arc<dyn DocumentStore>,
|
||||
wgpu_context: WgpuContext,
|
||||
wgpu_executor: WgpuExecutor,
|
||||
spawner: impl Spawn + Send + Sync + 'static,
|
||||
clock: Arc<dyn Clock>,
|
||||
scheduling: Scheduling,
|
||||
editor_wake: impl Fn() + Send + Sync + 'static,
|
||||
runtime_wake: impl Fn() + Send + Sync + 'static,
|
||||
) -> (Self, NodeRuntime) {
|
||||
@@ -54,7 +53,7 @@ impl DesktopWrapper {
|
||||
#[cfg(target_os = "linux")]
|
||||
let host = Host::Linux;
|
||||
let env = Environment { platform: Platform::Desktop, host };
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
let application_io = PlatformApplicationIo::new_with_executor(wgpu_executor);
|
||||
|
||||
let (editor, runtime) = Builder::new()
|
||||
.with_editor(
|
||||
@@ -64,13 +63,7 @@ impl DesktopWrapper {
|
||||
.with_resource_storage(resource_storage)
|
||||
.with_document_store(document_store),
|
||||
)
|
||||
.with_runtime(
|
||||
RuntimeBuilder::new()
|
||||
.with_wake(runtime_wake)
|
||||
.with_application_io(application_io)
|
||||
.with_clock(clock)
|
||||
.with_scheduling(scheduling),
|
||||
)
|
||||
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
|
||||
.with_spawner(spawner)
|
||||
.with_random_seed(random_seed)
|
||||
.build();
|
||||
|
||||
@@ -37,14 +37,11 @@ pub enum DesktopFrontendMessage {
|
||||
width: f64,
|
||||
height: f64,
|
||||
},
|
||||
UpdateUIScale {
|
||||
scale: f64,
|
||||
},
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(vello::Scene),
|
||||
PersistenceWritePreferences {
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
PersistenceLoadPreferences,
|
||||
@@ -71,8 +68,6 @@ pub enum DesktopFrontendMessage {
|
||||
WindowShowAll,
|
||||
Restart,
|
||||
LoadThirdPartyLicenses,
|
||||
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
|
||||
pub enum DesktopWrapperMessage {
|
||||
@@ -89,8 +84,6 @@ pub enum DesktopWrapperMessage {
|
||||
ClipboardReadResult { content: Option<String> },
|
||||
PointerLockMove { x: f64, y: f64 },
|
||||
LoadThirdPartyLicenses { text: String },
|
||||
|
||||
TmpUpdateViewport { x: f64, y: f64, width: f64, height: f64 },
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
|
||||
@@ -23,14 +23,11 @@ conversion = ["document-graph-storage/conversion", "dep:graph-craft", "dep:core-
|
||||
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
|
||||
zip = ["document-container/zip"]
|
||||
xz = ["document-container/xz"]
|
||||
# Live collaboration: `Gdd` hosts or joins a `peer_transport` session and mirrors hot ops and retired history to peers.
|
||||
network = ["dep:peer-transport"]
|
||||
default = ["conversion", "zip", "xz", "network"]
|
||||
default = ["conversion", "zip", "xz"]
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-graph-storage = { workspace = true, default-features = false }
|
||||
peer-transport = { workspace = true, optional = true }
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
|
||||
@@ -50,8 +50,4 @@ pub enum Error {
|
||||
/// An export marked a resource for embedding but its bytes were absent from the byte store.
|
||||
#[error("embedded resource {0} missing from the byte store")]
|
||||
MissingResource(ResourceHash),
|
||||
/// A packet for the collaboration session failed to encode.
|
||||
#[cfg(feature = "network")]
|
||||
#[error("network error: {0}")]
|
||||
Network(#[from] peer_transport::PacketError),
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
|
||||
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
|
||||
@@ -151,8 +151,6 @@ impl<L: Layout> Gdd<L> {
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
// An export is a copy taken out of the room; it does not reconnect on its own.
|
||||
shared: false,
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
@@ -160,13 +158,6 @@ impl<L: Layout> Gdd<L> {
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
|
||||
if !self.metadata.is_empty() {
|
||||
let mut facts = Vec::new();
|
||||
for fact in self.metadata.facts() {
|
||||
METADATA_CODEC.append(&mut facts, &fact)?;
|
||||
}
|
||||
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &facts)?;
|
||||
}
|
||||
|
||||
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ pub trait Layout {
|
||||
fn registry_basename(&self) -> &str;
|
||||
fn history_basename(&self) -> &str;
|
||||
fn hot_log_basename(&self) -> &str;
|
||||
/// What people state about the history beside it: users and their names, later labels and tags.
|
||||
fn metadata_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
@@ -41,9 +39,6 @@ impl Layout for GddV1Layout {
|
||||
fn hot_log_basename(&self) -> &str {
|
||||
"hot-log"
|
||||
}
|
||||
fn metadata_basename(&self) -> &str {
|
||||
"metadata"
|
||||
}
|
||||
fn resources_dir(&self) -> &str {
|
||||
"resources"
|
||||
}
|
||||
|
||||
+10
-108
@@ -10,17 +10,16 @@
|
||||
// gated off wasm to avoid unused-import warnings.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::{CommitError, NodeMetadataSource};
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, PeerId, Registry, Session, UserId};
|
||||
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::{ResourceHash, ResourceStorage};
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
pub mod codec;
|
||||
pub mod error;
|
||||
@@ -28,8 +27,6 @@ pub mod export;
|
||||
pub mod io;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
#[cfg(feature = "network")]
|
||||
pub mod network;
|
||||
pub mod persist;
|
||||
pub mod resource;
|
||||
pub mod session_state;
|
||||
@@ -55,8 +52,6 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
|
||||
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
/// Facts are appended one per line and folded on read, so the file is never rewritten.
|
||||
pub const METADATA_CODEC: Codec = Codec::JsonLines;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
@@ -70,8 +65,8 @@ pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
|
||||
/// read.
|
||||
/// `Clone` shares the working-copy container (`AnyContainer` is a handle) so a cloned handle reads and writes
|
||||
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared. A live collaboration session is
|
||||
/// not carried over.
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||
#[derive(Clone)]
|
||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) working: AnyContainer,
|
||||
@@ -80,74 +75,12 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
/// and synchronous.
|
||||
pub(crate) manifest: Manifest,
|
||||
/// What people state about the history, such as user names. Kept in its own file, merged last-writer-wins
|
||||
/// with every copy met, never folded or undone.
|
||||
pub(crate) metadata: HistoryMetadata,
|
||||
/// Wall clock in Unix-epoch milliseconds as the editor last reported it, so retirements can record when
|
||||
/// they happened. `None` when nothing ticks, as in the CLI or tests.
|
||||
pub(crate) wall_clock_ms: Option<f64>,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
||||
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
||||
pub(crate) network_view_settings: std::collections::BTreeMap<document_graph_storage::NetworkId, std::collections::BTreeMap<String, document_graph_storage::Value>>,
|
||||
/// Where resource bytes live. `None` means the working copy's own content-addressed store; the editor
|
||||
/// points this at its application-wide cache.
|
||||
pub(crate) byte_store: Option<Arc<dyn ResourceStorage>>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) network: Option<peer_transport::Replica>,
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) pending_persist: PendingPersist,
|
||||
/// What peers changed since the editor last took it, so it can reconcile its runtime mirror without a rebuild.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// When each closed interaction was first seen, by marker, so the retirement policy can age it. Not
|
||||
/// persisted: after a reopen everything pending is old enough.
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
/// When this peer last staged an op, so an interaction the editor left open can be closed once quiet.
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
/// Whether an op of this peer's own was staged since the last policy tick.
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
/// Whether the document should be in its room: set by sharing, cleared by disconnecting, persisted so
|
||||
/// a reopen reconnects.
|
||||
pub(crate) shared: bool,
|
||||
}
|
||||
|
||||
/// Whole-file rewrites deferred to the end of a poll, so a batch of remote packets costs one rewrite per
|
||||
/// file, not one per packet.
|
||||
#[cfg(feature = "network")]
|
||||
#[derive(Debug, Default, Clone, Copy)]
|
||||
pub(crate) struct PendingPersist {
|
||||
pub(crate) history: bool,
|
||||
pub(crate) hot_log: bool,
|
||||
pub(crate) snapshot: bool,
|
||||
}
|
||||
|
||||
impl<L: Layout + Clone> Clone for Gdd<L> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
session: self.session.clone(),
|
||||
working: self.working.clone(),
|
||||
layout: self.layout.clone(),
|
||||
manifest: self.manifest.clone(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
metadata: self.metadata.clone(),
|
||||
wall_clock_ms: self.wall_clock_ms,
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
byte_store: self.byte_store.clone(),
|
||||
shared: self.shared,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
@@ -165,10 +98,10 @@ impl<L: Layout + Default> Gdd<L> {
|
||||
|
||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||
pub fn create(path: &Path, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||
let layout = L::default();
|
||||
Self::create_in(working, layout, peer, user, document_uuid, editor_version, stdlib_version)
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,10 +136,6 @@ impl<L: Layout> Gdd<L> {
|
||||
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
|
||||
false => SessionState::default(),
|
||||
};
|
||||
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
|
||||
true => HistoryMetadata::fold(io::iter::<MetadataFact>(&working, layout.metadata_basename(), METADATA_CODEC).await?),
|
||||
false => HistoryMetadata::default(),
|
||||
};
|
||||
|
||||
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
@@ -231,12 +160,11 @@ impl<L: Layout> Gdd<L> {
|
||||
if let Some(rev) = session_state.last_broadcast_rev {
|
||||
session.publish_up_to(rev);
|
||||
}
|
||||
// Every arm must continue this peer's authored-op count too.
|
||||
|
||||
session.restore_hot_sequence(session_state.last_hot_sequence);
|
||||
session.restore_clock_counter(session_state.clock_counter);
|
||||
// Before the hot log replays, so a retired op in it is dropped rather than staged again.
|
||||
session.absorb_retired_marks(&session_state.retired_marks);
|
||||
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -246,36 +174,23 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
shared: session_state.shared,
|
||||
metadata,
|
||||
wall_clock_ms: None,
|
||||
byte_store: None,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||
/// the manifest and writes each payload with its recorded codec.
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, user: UserId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
pub fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState {
|
||||
peer_id: peer,
|
||||
user_id: user,
|
||||
user_id: UserId(peer.0),
|
||||
..Default::default()
|
||||
};
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_identity(peer, user);
|
||||
let session = Session::with_peer(peer);
|
||||
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
|
||||
|
||||
Ok(Self {
|
||||
@@ -285,19 +200,6 @@ impl<L: Layout> Gdd<L> {
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
metadata: HistoryMetadata::default(),
|
||||
wall_clock_ms: None,
|
||||
byte_store: None,
|
||||
shared: false,
|
||||
#[cfg(feature = "network")]
|
||||
network: None,
|
||||
#[cfg(feature = "network")]
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,359 +0,0 @@
|
||||
//! Live collaboration on the [`Gdd`] handle. `share` / `join` attach a [`Replica`]; the persist path
|
||||
//! then broadcasts staged hot ops, and retired deltas when hosting. `poll_peers` applies what peers
|
||||
//! send through the [`SyncTarget`] impl below, which persists it like local edits.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, RegistryDelta, ResourceHash, RetiredMarks, Rev, Session, Touched, UserId};
|
||||
use peer_transport::{Event, Replica, Role, SyncTarget, TargetError, Transport};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::{Gdd, PendingPersist};
|
||||
|
||||
/// What peers changed in the working registry since the editor last asked, so the editor can reconcile
|
||||
/// just the touched entities of its runtime mirror.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RemoteChanges {
|
||||
pub touched: Touched,
|
||||
/// A full sync replaced the working registry, so the touched set no longer bounds what changed and the mirror
|
||||
/// must be rebuilt.
|
||||
pub rebuilt: bool,
|
||||
}
|
||||
|
||||
impl RemoteChanges {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.touched.is_empty() && !self.rebuilt
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: RemoteChanges) {
|
||||
self.touched.extend(other.touched);
|
||||
self.rebuilt |= other.rebuilt;
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Takes what peers changed since the last call. Empty when nothing did.
|
||||
pub fn take_remote_changes(&mut self) -> RemoteChanges {
|
||||
std::mem::take(&mut self.remote_changes)
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn share(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::host(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
/// Connect to this document's room as host or guest, and remember it is shared so a reopen reconnects.
|
||||
pub fn connect(&mut self, transport: impl Transport + 'static, user: UserId) -> Result<(), Error> {
|
||||
self.network = Some(Replica::connect(transport, self.session.peer(), user));
|
||||
self.shared = true;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Whether the document is meant to be in its room; see [`connect`](Self::connect).
|
||||
pub fn is_shared(&self) -> bool {
|
||||
self.shared
|
||||
}
|
||||
|
||||
/// Take the host role if none is present once the grace period ends. See [`Replica::decide_role`].
|
||||
pub fn decide_role(&mut self) -> Option<Role> {
|
||||
self.network.as_mut().and_then(Replica::decide_role)
|
||||
}
|
||||
|
||||
pub fn join(&mut self, transport: impl Transport + 'static, user: UserId) {
|
||||
self.network = Some(Replica::guest(transport, self.session.peer(), user));
|
||||
}
|
||||
|
||||
/// Leaves the room. A host first retires every closed interaction, so finished work reaches history before
|
||||
/// the retirer leaves.
|
||||
pub fn leave(&mut self) {
|
||||
self.shared = false;
|
||||
if let Err(error) = self.persist_session_state() {
|
||||
log::error!("Persisting the session state before leaving failed: {error}");
|
||||
}
|
||||
self.disconnect();
|
||||
}
|
||||
|
||||
/// Drops the connection but keeps the document shared, for a transport that went down, so a reopen reconnects.
|
||||
pub fn disconnect(&mut self) {
|
||||
let closed = self.session.closed_interactions();
|
||||
if let Err(error) = self.retire_interactions(&closed) {
|
||||
log::error!("Retiring before leaving failed: {error}");
|
||||
}
|
||||
if let Some(mut replica) = self.network.take() {
|
||||
replica.leave();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.network.as_ref().map(Replica::role)
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.network.as_ref().is_none_or(Replica::is_synced)
|
||||
}
|
||||
|
||||
/// Announce this peer's display name to the room; a no-op when it has not changed or nobody is connected.
|
||||
pub fn set_name(&mut self, name: &str) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.set_name(name)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send this peer's pointer position, `None` when it left the viewport.
|
||||
pub fn send_cursor(&mut self, position: Option<peer_transport::CursorPosition>) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_cursor(position)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The other peers in the room; empty when the document is not connected.
|
||||
pub fn peers(&self) -> Vec<peer_transport::RemotePeer> {
|
||||
self.network.as_ref().map(|replica| replica.peers().cloned().collect()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Record that the runtime was rebuilt from the registry, so the next staged diff is taken against it.
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.session.mark_runtime_current();
|
||||
}
|
||||
|
||||
pub fn poll_peers(&mut self) -> Vec<Event> {
|
||||
let Some(mut replica) = self.network.take() else { return Vec::new() };
|
||||
let events = replica.poll(self);
|
||||
self.network = Some(replica);
|
||||
events
|
||||
}
|
||||
|
||||
/// Answer an [`Event::ResourceRequested`].
|
||||
pub fn send_resource(&mut self, to: peer_transport::TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), Error> {
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_resource(to, hash, bytes)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> SyncTarget for Gdd<L> {
|
||||
fn peer(&self) -> PeerId {
|
||||
self.session.peer()
|
||||
}
|
||||
|
||||
fn document_id(&self) -> Option<u64> {
|
||||
Some(self.manifest.document_id)
|
||||
}
|
||||
|
||||
fn adopt_document_id(&mut self, document_id: u64) -> Result<(), TargetError> {
|
||||
self.update_manifest(|manifest| manifest.document_id = document_id)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.session.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
self.session.retired_registry().clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
self.session.hot_log().to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
self.session.known_revs()
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.session.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta> {
|
||||
let deltas = <Session as SyncTarget>::deltas_unknown_to(&mut self.session, known);
|
||||
// The published frontier moved; it persists with the session state.
|
||||
self.pending_persist.snapshot |= !deltas.is_empty();
|
||||
deltas
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
self.session.load(registry, history, head)?;
|
||||
self.remote_changes.rebuilt = true;
|
||||
self.pending_persist = PendingPersist {
|
||||
history: true,
|
||||
hot_log: true,
|
||||
snapshot: true,
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// An op naming an entity not yet here is handed back for retry; only applied ops reach the hot frame log.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
// Recorded even if the apply fails: it may still have revived what it references.
|
||||
self.remote_changes.touched.record(&hot_op.op);
|
||||
if self.session.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
continue;
|
||||
}
|
||||
self.append_hot_frame(&hot_op)?;
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
|
||||
let incoming: HashSet<Rev> = deltas.iter().map(|delta| delta.id).collect();
|
||||
let length_before = self.session.history_len();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
SyncTarget::merge_remote(&mut self.session, deltas, retires, head)?;
|
||||
|
||||
// Whatever a peer sent is already shared, so it sits behind the published frontier and cannot be silently rewound.
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
|
||||
// A batch that only extended history, plus any merge delta joining it, is appended to the file; one that
|
||||
// sorted earlier deltas after it rewrites the file.
|
||||
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
|
||||
let appended = tail
|
||||
.iter()
|
||||
.all(|&rev| incoming.contains(&rev) || self.session.delta(rev).is_some_and(|delta| matches!(delta.kind, RegistryDelta::Merge { .. })));
|
||||
match appended {
|
||||
true => self.append_history_deltas(&tail)?,
|
||||
false => self.pending_persist.history = true,
|
||||
}
|
||||
self.pending_persist.hot_log |= !retires.is_empty();
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
|
||||
let length_before = self.session.history_len();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
let absorbed = SyncTarget::merge_divergent(&mut self.session, deltas, retires)?;
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
|
||||
// Appended when the tail is just the absorbed deltas and their merge; see `merge_remote`.
|
||||
let absorbed_ids: HashSet<Rev> = absorbed.iter().map(|delta| delta.id).collect();
|
||||
let tail: Vec<Rev> = self.session.history().skip(length_before).map(|delta| delta.id).collect();
|
||||
match tail.iter().all(|rev| absorbed_ids.contains(rev)) {
|
||||
true => self.append_history_deltas(&tail)?,
|
||||
false => self.pending_persist.history = true,
|
||||
}
|
||||
self.pending_persist.hot_log |= !retires.is_empty();
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(absorbed)
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
SyncTarget::retired_marks(&self.session)
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
let touched = self.session.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.hot_log = true;
|
||||
// Also writes the session state, which carries the marks.
|
||||
self.pending_persist.snapshot = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn metadata(&self) -> HistoryMetadata {
|
||||
self.metadata.clone()
|
||||
}
|
||||
|
||||
fn absorb_metadata(&mut self, remote: &HistoryMetadata) -> Result<bool, TargetError> {
|
||||
let landed = self.metadata.merge(remote);
|
||||
if landed.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
self.append_facts(&landed)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
|
||||
let touched = self.session.retract_hot_ops(ops);
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
|
||||
let touched = self.session.apply_head_move(moved)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.pending_persist.history = true;
|
||||
self.pending_persist.hot_log = true;
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.pending_persist.snapshot = true;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
let pending = std::mem::take(&mut self.pending_persist);
|
||||
|
||||
if pending.history {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
if pending.hot_log {
|
||||
self.rewrite_hot_log()?;
|
||||
}
|
||||
if pending.snapshot {
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
self.unstored_resources().into_iter().collect()
|
||||
}
|
||||
|
||||
fn store_resource(&mut self, _hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
self.hold_resource(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+59
-371
@@ -6,7 +6,7 @@
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use document_graph_storage::NodeMetadataSource;
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOp, MetadataFact, RegistryDelta, Rev, TimeStamp, UserId, Value, WallStamp};
|
||||
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
@@ -14,7 +14,7 @@ use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
@@ -35,16 +35,6 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Set the person using this device. A change re-registers the peer on its next staged batch, and the newer
|
||||
/// registration wins everywhere.
|
||||
pub fn set_user(&mut self, user: UserId) -> Result<(), Error> {
|
||||
if self.session.user() == user {
|
||||
return Ok(());
|
||||
}
|
||||
self.session.set_user(user);
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Edit the cached manifest and persist it. Always JSON, synchronous.
|
||||
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
|
||||
edit(&mut self.manifest);
|
||||
@@ -72,7 +62,10 @@ impl<L: Layout> Gdd<L> {
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<document_graph_storage::Declarations, Error> {
|
||||
let (hot_ops, conversion) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
@@ -87,43 +80,36 @@ impl<L: Layout> Gdd<L> {
|
||||
/// the whole document and diffing it against the working registry.
|
||||
///
|
||||
/// Otherwise identical to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot): each op becomes a
|
||||
/// hot frame, is broadcast to any session, and the proto-node declaration bytes go to the byte store.
|
||||
/// hot frame, and the proto-node declaration bytes go to the byte store.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_constructed_ops(
|
||||
&mut self,
|
||||
ops: Vec<document_graph_storage::RegistryDelta>,
|
||||
declaration_bytes: &document_graph_storage::from_runtime::DeclarationBytes,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
) -> Result<(), Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Stage raw registry ops as hot ops, for callers that don't go through the runtime diff.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, Error> {
|
||||
let hot_ops = self.session.stage_computed_ops(ops.into_iter().collect())?;
|
||||
self.persist_staged(&hot_ops)?;
|
||||
Ok(hot_ops)
|
||||
}
|
||||
|
||||
/// Every staged hot op ends here: the frame that survives a crash, then the broadcast that reaches the room.
|
||||
fn persist_staged(&mut self, hot_ops: &[HotOp]) -> Result<(), Error> {
|
||||
if hot_ops.iter().any(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
self.own_staged_since_tick = true;
|
||||
}
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_hot_ops(hot_ops)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
|
||||
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
|
||||
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
|
||||
/// are no pending hot ops.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
self.retire_inner(up_to, true)
|
||||
}
|
||||
|
||||
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
|
||||
/// durable history. Convenience for callers that produce a whole interaction atomically (tests, and any
|
||||
/// one-shot commit). Equivalent to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot) followed
|
||||
@@ -153,34 +139,24 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist freshly-staged hot ops and retire exactly them into durable history as one unit. Frames are
|
||||
/// appended first, so a crash before retirement still recovers the work. Returns the retired `Rev`s;
|
||||
/// on a peer that does not retire the ops stay hot.
|
||||
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
|
||||
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
|
||||
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
|
||||
/// retired `Rev`s. A no-op when nothing was staged.
|
||||
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
if hot_ops.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
|
||||
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let ids: Vec<_> = hot_ops.iter().map(HotOp::id).collect();
|
||||
let revs = self.session.retire_hot_ops(&ids)?;
|
||||
// Marked before the history frames are written, so the boundary is on disk with them.
|
||||
if interaction_end && let Some(&last) = revs.last() {
|
||||
self.session.mark_interaction_end(last);
|
||||
}
|
||||
self.finish_retirement(&revs, &ids)?;
|
||||
Ok(revs)
|
||||
self.retire_inner(last.timestamp, interaction_end)
|
||||
}
|
||||
|
||||
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
|
||||
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
|
||||
/// preserves replay order without scanning the whole history.
|
||||
pub(crate) fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
|
||||
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for &rev in revs {
|
||||
let Some(delta) = self.session.delta(rev) else {
|
||||
@@ -195,7 +171,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
|
||||
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
|
||||
/// the whole history file is rewritten in topological order. O(history), fine for occasional user
|
||||
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
|
||||
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: Value) -> Result<(), Error> {
|
||||
if self.session.annotate_delta(rev, key, value) {
|
||||
@@ -208,7 +184,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
pub(crate) fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in self.session.history() {
|
||||
self.manifest.codecs.history.append(&mut buffer, delta)?;
|
||||
@@ -217,58 +193,7 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What people state about the history, such as user names.
|
||||
pub fn metadata(&self) -> &HistoryMetadata {
|
||||
&self.metadata
|
||||
}
|
||||
|
||||
/// Record a fact about a user at wall time `wall_ms`, persisted and told to the room. Returns whether it
|
||||
/// changed anything.
|
||||
pub fn record_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms.max(0.) as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.set_user_attribute(user, key, value, stamp) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.append_facts(&[fact])?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_metadata(&self.metadata)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Record a fact about a rev, such as a label or tag on the interaction it closes. Otherwise like
|
||||
/// [`record_user_attribute`](Self::record_user_attribute).
|
||||
pub fn record_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
|
||||
let stamp = WallStamp {
|
||||
ms: wall_ms.max(0.) as u64,
|
||||
peer: self.session.peer(),
|
||||
};
|
||||
let Some(fact) = self.metadata.set_rev_attribute(rev, key, value, stamp) else {
|
||||
return Ok(false);
|
||||
};
|
||||
self.append_facts(&[fact])?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.send_metadata(&self.metadata)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Append facts to the metadata file, one line each; the file is never rewritten.
|
||||
pub(crate) fn append_facts(&mut self, facts: &[MetadataFact]) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for fact in facts {
|
||||
METADATA_CODEC.append(&mut buffer, fact)?;
|
||||
}
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
user_id: self.session.user(),
|
||||
@@ -277,7 +202,6 @@ impl<L: Layout> Gdd<L> {
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
last_hot_sequence: self.session.last_hot_sequence(),
|
||||
shared: self.shared,
|
||||
retired_marks: self.session.retired_marks().clone(),
|
||||
clock_counter: self.session.clock_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
@@ -289,7 +213,7 @@ impl<L: Layout> Gdd<L> {
|
||||
|
||||
/// Re-snapshot the retired registry to `registry.bin`. `Session::load` trusts it to match the persisted `head`
|
||||
/// and replays the hot log on top, so it must hold no hot op, and any cursor move must re-persist it.
|
||||
pub(crate) fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.retired_registry())?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -318,281 +242,45 @@ impl<L: Layout> Gdd<L> {
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
pub(crate) fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How many closed interactions must be waiting before they retire. Retiring later fuses more of a gesture
|
||||
/// into one delta and leaves more for undo to rewind silently.
|
||||
pub const RETIRE_AFTER_INTERACTIONS: usize = 10;
|
||||
/// How long a closed interaction sits before it may retire, so every peer has seen all of it.
|
||||
pub const RETIRE_MIN_AGE_MS: f64 = 2_000.0;
|
||||
/// The longest anything waits: a quiet session still retires, and an interaction with a gap in its author's
|
||||
/// run retires with what arrived.
|
||||
pub const RETIRE_MAX_AGE_MS: f64 = 60_000.0;
|
||||
|
||||
/// Closes this peer's open interaction, if any, with a marker broadcast like any other hot op. The editor
|
||||
/// calls this at each undo-step boundary.
|
||||
pub fn end_interaction(&mut self) -> Result<(), Error> {
|
||||
let staged = self.session.end_interaction()?;
|
||||
self.persist_staged(&staged)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo this peer's latest interaction while it is still hot: its ops leave the hot log here, and on every
|
||||
/// peer the retraction reaches, and never retire. `None` means the step already retired and undo has to
|
||||
/// move the cursor. What the ops named lands in the remote changes, so the mirror picks up what others
|
||||
/// wrote there meanwhile.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
|
||||
let Some(document_graph_storage::Retraction { ids, touched, ops }) = self.session.retract_interaction()? else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.own_last_staged_ms = None;
|
||||
#[cfg(feature = "network")]
|
||||
self.remote_changes.touched.extend(touched);
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = touched;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retraction(&ids)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = ids;
|
||||
Ok(Some(ops))
|
||||
}
|
||||
|
||||
/// Undo this peer's latest retired step, the one [`Session::latest_own_interaction`] names, through
|
||||
/// [`drop_step`](Self::drop_step). `None` when this peer has no retired step of its own on the line.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn undo_retired_step(&mut self) -> Result<Option<Rev>, Error> {
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
self.drop_step(rev)?;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
/// Drop a retired interaction out of the line, later steps minted again on its parent; see
|
||||
/// [`Session::drop_interaction`]. The retirer does it, records what it named in the remote changes and
|
||||
/// tells the room; anyone else asks the retirer and sees the head move come back through the poll.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn drop_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.drop_interaction(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.rewrite_history()?;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, false)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the head to an ancestor in a session, everything since staying as a branch; see
|
||||
/// [`Session::move_head_to`]. The retirer does it and tells the room; anyone else asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
if let Some(head) = self.session.head_rev() {
|
||||
self.session.publish_up_to(head);
|
||||
}
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_move(rev)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Redo a step [`undo_retired_step`](Self::undo_retired_step) dropped, as a copy on top of the line.
|
||||
/// The retirer does it; anyone else asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let revs = self.session.restore_interaction(rev)?;
|
||||
let deltas: Vec<Delta> = revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
for delta in &deltas {
|
||||
self.remote_changes.touched.record(&delta.kind);
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.session.publish_up_to(last);
|
||||
}
|
||||
self.rewrite_history()?;
|
||||
self.rewrite_hot_log()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_retired(&deltas, &[])?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_undo(rev, true)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage ops a retraction took back as a fresh interaction, recording them as changes for the mirror:
|
||||
/// redoing a retracted step is a new edit to everyone, this peer included.
|
||||
pub fn restage_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<(), Error> {
|
||||
#[cfg(feature = "network")]
|
||||
for op in &ops {
|
||||
self.remote_changes.touched.record(op);
|
||||
}
|
||||
self.stage_ops(ops)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every interaction the policy says is due at `now_ms`, the wall clock in milliseconds that retirements
|
||||
/// also record: closed interactions that have waited [`RETIRE_MIN_AGE_MS`](Self::RETIRE_MIN_AGE_MS), once
|
||||
/// [`RETIRE_AFTER_INTERACTIONS`](Self::RETIRE_AFTER_INTERACTIONS) of them are waiting or the oldest has waited
|
||||
/// [`RETIRE_MAX_AGE_MS`](Self::RETIRE_MAX_AGE_MS). Open interactions never retire. The editor calls this every
|
||||
/// frame with whether it is between steps; a peer that does not retire only closes its own quiet interaction.
|
||||
pub fn retire_due(&mut self, now_ms: f64, idle: bool) -> Result<Vec<Rev>, Error> {
|
||||
// The editor passes the wall clock, which retirements record as when a step happened.
|
||||
self.wall_clock_ms = Some(now_ms);
|
||||
// An interaction the editor never closed, or one cut off by a reopen, closes once quiet, but only between
|
||||
// steps: a pause mid-gesture must not split what undo takes back as one.
|
||||
if self.own_staged_since_tick {
|
||||
self.own_staged_since_tick = false;
|
||||
self.own_last_staged_ms = Some(now_ms);
|
||||
} else if idle && self.own_last_staged_ms.is_some_and(|last| now_ms - last >= Self::RETIRE_MIN_AGE_MS) {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
}
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let closed = self.session.closed_interactions();
|
||||
let mut seen = std::mem::take(&mut self.interactions_seen);
|
||||
let mut due = Vec::new();
|
||||
let mut oldest_age: f64 = 0.0;
|
||||
for interaction in &closed {
|
||||
let Some(&marker) = interaction.ops.last() else { continue };
|
||||
let age = now_ms - *seen.entry(marker).or_insert(now_ms);
|
||||
if age >= Self::RETIRE_MIN_AGE_MS && (interaction.contiguous || age >= Self::RETIRE_MAX_AGE_MS) {
|
||||
due.push(interaction.clone());
|
||||
oldest_age = oldest_age.max(age);
|
||||
}
|
||||
}
|
||||
seen.retain(|marker, _| closed.iter().any(|interaction| interaction.ops.last() == Some(marker)));
|
||||
self.interactions_seen = seen;
|
||||
|
||||
if due.len() >= Self::RETIRE_AFTER_INTERACTIONS || oldest_age >= Self::RETIRE_MAX_AGE_MS {
|
||||
self.retire_interactions(&due)
|
||||
} else {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// Close this peer's open interaction and retire every closed one, whoever authored it. The undo path calls
|
||||
/// this first so the interaction being undone is in history; a peer that does not retire only closes its own.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
self.end_interaction()?;
|
||||
self.own_last_staged_ms = None;
|
||||
let closed = self.session.closed_interactions();
|
||||
self.retire_interactions(&closed)
|
||||
}
|
||||
|
||||
/// Retire the given closed interactions, each as one undo step, in one history append and one
|
||||
/// broadcast. A no-op for a peer that leaves retirement to the session host.
|
||||
pub(crate) fn retire_interactions(&mut self, interactions: &[document_graph_storage::ClosedInteraction]) -> Result<Vec<Rev>, Error> {
|
||||
if !self.retires_locally() || interactions.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut revs = Vec::new();
|
||||
let mut retired_hot_ops = Vec::new();
|
||||
for interaction in interactions {
|
||||
revs.extend(self.session.retire_interaction(interaction)?);
|
||||
retired_hot_ops.extend(interaction.ops.iter().copied());
|
||||
}
|
||||
self.finish_retirement(&revs, &retired_hot_ops)?;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Working-copy checkpoint: retire every hot op stamped at or before `up_to`, whatever its author or
|
||||
/// interaction state. For callers that own the whole log; a session uses [`retire_interactions`](Self::retire_interactions).
|
||||
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
|
||||
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
|
||||
/// re-snapshot the registry. Synchronous.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
|
||||
if !self.retires_locally() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let retired_hot_ops = self.session.hot_ops_up_to(up_to);
|
||||
let revs = self.session.retire(up_to)?;
|
||||
self.finish_retirement(&revs, &retired_hot_ops)?;
|
||||
Ok(revs)
|
||||
self.retire_inner(up_to, false)
|
||||
}
|
||||
|
||||
/// What every retirement ends with: the published frontier moves, the deltas reach the history file,
|
||||
/// the hot log and snapshot are rewritten, and the room hears about it.
|
||||
fn finish_retirement(&mut self, new_revs: &[Rev], retired_hot_ops: &[document_graph_storage::HotOpId]) -> Result<(), Error> {
|
||||
// Stamped before the frames are written, so the time is on disk and in the broadcast.
|
||||
if let Some(wall_ms) = self.wall_clock_ms
|
||||
&& !new_revs.is_empty()
|
||||
{
|
||||
self.session.stamp_retired_at(new_revs, wall_ms as u64);
|
||||
}
|
||||
// These deltas are about to reach peers, so the published frontier moves with them: rewinding a commit
|
||||
// peers hold would silently diverge, so undo past it moves the shared head instead. Set before the
|
||||
// persists below so it survives a reopen.
|
||||
#[cfg(feature = "network")]
|
||||
if self.network.is_some()
|
||||
&& let Some(&last) = new_revs.last()
|
||||
{
|
||||
self.session.publish_up_to(last);
|
||||
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
|
||||
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
|
||||
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
let new_revs = self.session.retire(up_to)?;
|
||||
|
||||
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
|
||||
if interaction_end && let Some(&last) = new_revs.last() {
|
||||
self.session.mark_interaction_end(last);
|
||||
}
|
||||
|
||||
if !new_revs.is_empty() {
|
||||
self.append_history_deltas(new_revs)?;
|
||||
self.append_history_deltas(&new_revs)?;
|
||||
}
|
||||
|
||||
self.rewrite_hot_log()?;
|
||||
// Rewrite hot log with whatever survived retirement.
|
||||
let mut hot_buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
|
||||
}
|
||||
self.working
|
||||
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
|
||||
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
|
||||
#[cfg(feature = "network")]
|
||||
if let Some(replica) = &mut self.network {
|
||||
let deltas: Vec<_> = new_revs.iter().filter_map(|&rev| self.session.delta(rev).cloned()).collect();
|
||||
replica.broadcast_retired(&deltas, retired_hot_ops)?;
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
let _ = retired_hot_ops;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// Guests leave retirement to the host and keep their hot ops until its retired deltas arrive.
|
||||
fn retires_locally(&self) -> bool {
|
||||
#[cfg(feature = "network")]
|
||||
{
|
||||
self.network.as_ref().is_none_or(|replica| replica.role() == peer_transport::Role::Host)
|
||||
}
|
||||
#[cfg(not(feature = "network"))]
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn rewrite_hot_log(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, hot_op)?;
|
||||
}
|
||||
self.working.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
Ok(new_revs)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use graphene_resource::ResourceFuture;
|
||||
@@ -91,35 +90,6 @@ impl<L: Layout> Gdd<L> {
|
||||
{
|
||||
ResourceProxy(self.working.clone(), self.layout.clone())
|
||||
}
|
||||
|
||||
/// Point resource lookups at an external store, for an embedder keeping one cache for every open document.
|
||||
pub fn set_byte_store(&mut self, byte_store: Arc<dyn ResourceStorage>) {
|
||||
self.byte_store = Some(byte_store);
|
||||
}
|
||||
|
||||
/// Whether this document's resource bytes are on hand, in whichever store backs it.
|
||||
pub(crate) fn holds_resource(&self, hash: &ResourceHash) -> bool {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => byte_store.contains(hash),
|
||||
None => self.working.exists_non_blocking(&self.layout.resource_path(hash)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Put resource bytes into whichever store backs this document.
|
||||
pub(crate) fn hold_resource(&self, bytes: &[u8]) -> Result<(), ContainerError> {
|
||||
match &self.byte_store {
|
||||
Some(byte_store) => {
|
||||
byte_store.store(bytes);
|
||||
Ok(())
|
||||
}
|
||||
None => self.working.write_non_blocking(&self.layout.resource_path(&ResourceHash::from(bytes)), bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resources the registry or its history names whose bytes are not on hand.
|
||||
pub(crate) fn unstored_resources(&self) -> Vec<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes().into_iter().filter(|hash| !self.holds_resource(hash)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
@@ -133,12 +103,6 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
||||
|
||||
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -34,6 +34,9 @@ pub struct SessionState {
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||
#[serde(default)]
|
||||
@@ -42,12 +45,6 @@ pub struct SessionState {
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default)]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, Value>>,
|
||||
/// The last hot op sequence this peer authored, so a reopen never reuses one.
|
||||
#[serde(default)]
|
||||
pub last_hot_sequence: HotSequence,
|
||||
/// Whether the document was in its room when last persisted, so a reopen reconnects.
|
||||
#[serde(default)]
|
||||
pub shared: bool,
|
||||
/// The retired hot op marks, so a late copy re-sent after a reopen is dropped rather than retired again.
|
||||
#[serde(default)]
|
||||
pub retired_marks: RetiredMarks,
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
// History metadata: persisted with the working copy and merged with every copy met.
|
||||
// Needs the network feature for a session and the runtime conversion for staging ops.
|
||||
#![cfg(all(feature = "conversion", feature = "network"))]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::from_runtime::DeclarationBytes;
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, Rev, TimeStamp, UserId, rev_attr, user_attr};
|
||||
use peer_transport::mock::MockNetwork;
|
||||
|
||||
const NOW_MS: f64 = 1_700_000_000_000.;
|
||||
|
||||
async fn document(peer: u64, user: u64) -> GddV1 {
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(peer), UserId(user), 1, "editor".into(), "stdlib".into()).expect("create")
|
||||
}
|
||||
|
||||
/// Let the room settle: greetings, the sync handshake and whatever was broadcast.
|
||||
fn settle(network: &mut MockNetwork, peers: &mut [&mut GddV1]) {
|
||||
for _ in 0..16 {
|
||||
for peer in peers.iter_mut() {
|
||||
peer.poll_peers();
|
||||
}
|
||||
network.deliver_all();
|
||||
}
|
||||
for peer in peers.iter_mut() {
|
||||
peer.poll_peers();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recorded_name_survives_a_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10).await;
|
||||
assert!(gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
|
||||
assert!(
|
||||
!gdd.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"),
|
||||
"the same name is no change"
|
||||
);
|
||||
|
||||
let step = Rev::new(7).expect("non-zero");
|
||||
assert!(gdd.record_rev_attribute(step, rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record"));
|
||||
assert!(gdd.record_rev_attribute(step, "tag:v1", true.into(), NOW_MS).expect("record"));
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open");
|
||||
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
|
||||
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"), "a label appended after the name is folded back in");
|
||||
assert_eq!(reopened.metadata().rev_tags(step), vec!["v1"]);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_reach_the_room_with_the_sync_and_as_they_change() {
|
||||
futures::executor::block_on(async {
|
||||
let mut host = document(1, 10).await;
|
||||
let mut guest = document(2, 20).await;
|
||||
host.record_user_attribute(UserId(10), user_attr::NAME, "Ada".into(), NOW_MS).expect("record");
|
||||
// A name given before joining travels with the joiner and reaches the host.
|
||||
guest.record_user_attribute(UserId(20), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
|
||||
|
||||
let mut network = MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(10));
|
||||
guest.join(guest_endpoint, UserId(20));
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
|
||||
assert!(guest.is_synced());
|
||||
assert_eq!(guest.metadata().user_name(UserId(10)), Some("Ada"), "the host's record came with the sync");
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Bea"), "the guest's record came back to the host");
|
||||
|
||||
// A rename while in the room goes round on its own.
|
||||
assert!(guest.record_user_attribute(UserId(20), user_attr::NAME, "Beatrix".into(), NOW_MS + 5_000.).expect("record"));
|
||||
settle(&mut network, &mut [&mut host, &mut guest]);
|
||||
assert_eq!(host.metadata().user_name(UserId(20)), Some("Beatrix"));
|
||||
assert_eq!(host.metadata(), guest.metadata(), "both copies hold the same record");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retirement_records_when_it_happened() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = document(1, 10).await;
|
||||
// The editor's per-frame tick is where the wall clock comes from.
|
||||
gdd.retire_due(NOW_MS, true).expect("tick");
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
gdd.stage_constructed_ops(
|
||||
vec![RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}],
|
||||
&DeclarationBytes::default(),
|
||||
&byte_store,
|
||||
)
|
||||
.expect("stage");
|
||||
let everything = TimeStamp {
|
||||
counter: u64::MAX,
|
||||
peer: PeerId(u64::MAX),
|
||||
};
|
||||
let revs = gdd.retire(everything).expect("retire");
|
||||
assert!(!revs.is_empty());
|
||||
for rev in revs {
|
||||
let delta = gdd.session().delta(rev).expect("retired delta");
|
||||
assert_eq!(delta.retired_at(), Some(NOW_MS as u64));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp, UserId};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -44,7 +44,7 @@ fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), UserId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()) {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
@@ -82,7 +82,7 @@ fn open_in_rejects_wrong_format_magic() {
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), UserId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
@@ -97,7 +97,7 @@ fn manifest_returns_what_create_in_wrote() {
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
@@ -112,7 +112,7 @@ fn update_manifest_changes_visible_after_reopen() {
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||
// produces one network in the registry.
|
||||
@@ -139,7 +139,7 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||
let early = HotOp {
|
||||
@@ -187,7 +187,7 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Retire one op so there is a real retired rev to mark as published.
|
||||
let op = HotOp {
|
||||
@@ -218,7 +218,7 @@ fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
@@ -246,7 +246,7 @@ fn export_zip_round_trips_via_deserialize() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), UserId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
@@ -271,7 +271,7 @@ fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
@@ -294,7 +294,7 @@ fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), UserId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -324,7 +324,7 @@ fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), UserId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -353,7 +353,7 @@ fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
@@ -377,7 +377,7 @@ fn export_carries_resources() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), UserId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
@@ -405,7 +405,7 @@ fn embed_all_resources_materializes_link_only_resource() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), UserId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||
// byte store; the working copy never holds them.
|
||||
@@ -470,7 +470,7 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||
let payload = b"embedded bytes in the cache";
|
||||
@@ -511,7 +511,7 @@ fn export_round_trips_unretired_hot_ops() {
|
||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), UserId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::ResourceHash::from(&payload[..]);
|
||||
@@ -564,7 +564,7 @@ fn open_in_rejects_future_format_version() {
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::Postcard);
|
||||
@@ -585,7 +585,7 @@ fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), UserId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
@@ -627,7 +627,7 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -680,7 +680,7 @@ fn declarations_round_trip_through_byte_store() {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), UserId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
@@ -708,7 +708,7 @@ fn an_export_without_history_drops_tombstones() {
|
||||
use document_graph_storage::{Network, NetworkId, RegistryDelta};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), UserId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xAC, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let id = NetworkId(7);
|
||||
gdd.stage_constructed_ops(vec![RegistryDelta::AddNetwork { id, network: Network::default() }], &Default::default(), &empty_byte_store())
|
||||
.unwrap();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry, UserId};
|
||||
use document_graph_storage::{NoMetadata, PeerId, Registry};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
@@ -25,7 +25,7 @@ fn network_with_one_node() -> NodeNetwork {
|
||||
/// A whole-document stage after a recorded batch stages nothing new: restating the batch would fail on the node it added.
|
||||
#[test]
|
||||
fn restaging_the_whole_document_after_a_batch_stages_nothing() {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), UserId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(21), 1, "ed".into(), "std".into()).unwrap();
|
||||
let store = HashMapResourceStorage::new();
|
||||
let resources = ResourceRegistry::new();
|
||||
gdd.stage_runtime_snapshot(&NodeNetwork::default(), &NoMetadata, &resources, &store)
|
||||
@@ -57,7 +57,7 @@ fn a_reopen_keeps_unretired_hot_ops_out_of_the_retired_snapshot() {
|
||||
attributes: Default::default(),
|
||||
};
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), UserId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(22), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.apply_hot_op(set(1, 1)).unwrap();
|
||||
gdd.apply_hot_op(set(2, 2)).unwrap();
|
||||
gdd.retire(TimeStamp { counter: 1, peer: PeerId(22) }).unwrap();
|
||||
@@ -80,24 +80,28 @@ fn a_reopen_continues_the_hot_op_sequence() {
|
||||
value: Some(Value::from(serde_json::json!(value))),
|
||||
},
|
||||
};
|
||||
fn stage(gdd: &mut GddV1, op: RegistryDelta) -> u64 {
|
||||
gdd.stage_constructed_ops(vec![op], &Default::default(), &HashMapResourceStorage::new()).unwrap();
|
||||
gdd.session().hot_log().last().unwrap().sequence.0
|
||||
}
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), UserId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
gdd.stage_ops([set(1)]).unwrap();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(23), 1, "ed".into(), "std".into()).unwrap();
|
||||
stage(&mut gdd, set(1));
|
||||
let up_to = gdd.session().hot_log().last().unwrap().timestamp;
|
||||
gdd.retire(up_to).unwrap();
|
||||
let last = gdd.stage_ops([set(2)]).unwrap().last().unwrap().sequence;
|
||||
let last = stage(&mut gdd, set(2));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.stage_ops([set(3)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
assert_eq!(stage(&mut reopened, set(3)), last + 1);
|
||||
|
||||
let up_to = reopened.session().hot_log().last().unwrap().timestamp;
|
||||
reopened.retire(up_to).unwrap();
|
||||
let last = reopened.session().last_hot_sequence();
|
||||
let last = reopened.session().last_hot_sequence().0;
|
||||
let clock = reopened.session().clock_counter();
|
||||
let (working, layout) = reopened.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.unwrap();
|
||||
assert_eq!(reopened.session().clock_counter(), clock, "the clock carries over");
|
||||
assert_eq!(reopened.stage_ops([set(4)]).unwrap()[0].sequence.0, last.0 + 1);
|
||||
assert_eq!(stage(&mut reopened, set(4)), last + 1);
|
||||
});
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// Needs the runtime conversion for `stage_constructed_ops` and the network feature for a session.
|
||||
#![cfg(all(feature = "conversion", feature = "network"))]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::from_runtime::DeclarationBytes;
|
||||
use document_graph_storage::{Network, NetworkId, PeerId, RegistryDelta, UserId};
|
||||
use peer_transport::mock::MockNetwork;
|
||||
|
||||
/// Every staging path has to reach the room. Pins a regression where the recorded-batch path persisted its hot frames
|
||||
/// but never sent them.
|
||||
#[test]
|
||||
fn staging_a_constructed_batch_reaches_the_room() {
|
||||
futures::executor::block_on(async {
|
||||
let mut host = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
|
||||
let mut network = MockNetwork::new(1);
|
||||
let host_endpoint = network.endpoint();
|
||||
let guest_endpoint = network.endpoint();
|
||||
let (host_id, guest_id) = (host_endpoint.id(), guest_endpoint.id());
|
||||
host.share(host_endpoint, UserId(1));
|
||||
network.connect(host_id);
|
||||
network.connect(guest_id);
|
||||
|
||||
// Greet the guest so the host can send to it, and get the hello out of the way.
|
||||
host.poll_peers();
|
||||
network.deliver_all();
|
||||
assert_eq!(network.pending(), 0);
|
||||
|
||||
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
|
||||
let staged = host
|
||||
.stage_constructed_ops(
|
||||
vec![RegistryDelta::AddNetwork {
|
||||
id: NetworkId(9),
|
||||
network: Network::default(),
|
||||
}],
|
||||
&DeclarationBytes::default(),
|
||||
&byte_store,
|
||||
)
|
||||
.expect("stage");
|
||||
|
||||
assert!(!staged.is_empty(), "the staged hot ops come back for the caller");
|
||||
assert!(network.pending() > 0, "a staged batch must be broadcast to the room");
|
||||
});
|
||||
}
|
||||
@@ -211,8 +211,6 @@ pub enum RegistryDelta {
|
||||
Merge {
|
||||
extra_parents: Vec<Rev>,
|
||||
},
|
||||
/// Changes nothing and only carries its hot op's attributes, such as the end of an interaction staged after its last
|
||||
/// write. Retirement drops it.
|
||||
Meta,
|
||||
// Allow for future delta types without a model change
|
||||
Other(Value),
|
||||
|
||||
@@ -2,8 +2,8 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::hash::Hash;
|
||||
|
||||
use crate::{
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId,
|
||||
NodeInput, PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
|
||||
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
|
||||
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -16,7 +16,7 @@ pub struct Document {
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// The stamps of the hot log's ops, so a re-announced op is recognised without a scan.
|
||||
pub(crate) hot_timestamps: HashSet<TimeStamp>,
|
||||
/// Which hot ops are done with (retired, or taken back by their author), so a late copy is dropped.
|
||||
/// Which hot ops are retired into history, so a late copy is dropped.
|
||||
pub(crate) retired: RetiredMarks,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
@@ -112,36 +112,12 @@ impl Document {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record newly retired hot ops, dropping any the hot log still holds. Returns what the dropped ops named.
|
||||
pub(crate) fn mark_retired(&mut self, retired: impl IntoIterator<Item = HotOpId>) -> crate::Touched {
|
||||
self.retired.extend(retired);
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
|
||||
/// Take on a peer's marks as well as this peer's. Returns what the dropped ops named.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> crate::Touched {
|
||||
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
|
||||
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
|
||||
self.retired.absorb(remote);
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
|
||||
/// Take back hot ops for good, re-deriving the working registry without them, since a commuting op
|
||||
/// cannot be undone in place. Returns what the ops named and the ops themselves.
|
||||
pub(crate) fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> (crate::Touched, Vec<HotOp>) {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let taken: Vec<HotOp> = self.hot_log.extract_if(.., |hot_op| wanted.contains(&hot_op.id())).collect();
|
||||
taken.iter().for_each(|hot_op| _ = self.hot_timestamps.remove(&hot_op.timestamp));
|
||||
self.retired.extend(ids.iter().copied());
|
||||
|
||||
let mut touched = crate::Touched::default();
|
||||
for hot_op in &taken {
|
||||
touched.record(&hot_op.op);
|
||||
}
|
||||
if !taken.is_empty() {
|
||||
self.rebuild_working();
|
||||
}
|
||||
(touched, taken)
|
||||
}
|
||||
|
||||
/// Bring the stamp index back in line after the hot log was filtered as a whole.
|
||||
pub(crate) fn resync_hot_timestamps(&mut self) {
|
||||
self.hot_timestamps = self.hot_log.iter().map(|hot_op| hot_op.timestamp).collect();
|
||||
@@ -157,17 +133,17 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop retired hot ops and re-derive working without them: a retired op's effect returns with its delta.
|
||||
fn drop_retired_hot_ops(&mut self) -> crate::Touched {
|
||||
/// Drop retired hot ops and re-derive working without them: their effect returns with their deltas.
|
||||
fn drop_retired_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
let retired = &self.retired;
|
||||
let dropped: Vec<HotOp> = self.hot_log.extract_if(.., |hot_op| retired.covers(hot_op.id())).collect();
|
||||
let mut touched = crate::Touched::default();
|
||||
if !dropped.is_empty() {
|
||||
dropped.iter().for_each(|hot_op| touched.record(&hot_op.op));
|
||||
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
|
||||
let dropped = self.hot_log.len() != before;
|
||||
if dropped {
|
||||
self.resync_hot_timestamps();
|
||||
self.rebuild_working();
|
||||
}
|
||||
touched
|
||||
dropped
|
||||
}
|
||||
|
||||
/// Apply a retired commit and record it in history.
|
||||
|
||||
@@ -37,11 +37,6 @@ impl History {
|
||||
history
|
||||
}
|
||||
|
||||
/// Where `rev` sits in the file order, if it is here.
|
||||
pub(crate) fn position(&self, rev: Rev) -> Option<usize> {
|
||||
self.index.get(&rev).copied()
|
||||
}
|
||||
|
||||
pub fn get(&self, rev: Rev) -> Option<&Delta> {
|
||||
self.index.get(&rev).map(|&position| &self.deltas[position])
|
||||
}
|
||||
@@ -55,15 +50,6 @@ impl History {
|
||||
&self.resource_hashes
|
||||
}
|
||||
|
||||
/// Whether the deltas from `from` on already sit in canonical order, as a single-parent chain off the delta
|
||||
/// before them, as a retirement appends: each link is the sort's only candidate at its step.
|
||||
pub(crate) fn extends_canonically(&self, from: usize) -> bool {
|
||||
(from..self.deltas.len()).all(|position| {
|
||||
let delta = &self.deltas[position];
|
||||
delta.parent == position.checked_sub(1).map(|previous| self.deltas[previous].id) && !matches!(delta.kind, RegistryDelta::Merge { .. })
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -104,17 +90,22 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// The delta at `position` in topological order.
|
||||
pub(crate) fn at(&self, position: usize) -> Option<&Delta> {
|
||||
self.deltas.get(position)
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
///
|
||||
/// Deterministic: peers that absorb the same delta set end up with byte-identical history, whatever the
|
||||
/// arrival order.
|
||||
pub(crate) fn canonical_sort(&mut self) {
|
||||
fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
@@ -168,37 +159,6 @@ impl History {
|
||||
seen
|
||||
}
|
||||
|
||||
pub(crate) fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
|
||||
self.ancestors([descendant]).contains(&ancestor)
|
||||
}
|
||||
|
||||
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
|
||||
/// so it can locate the divergence point within a factor of two of the true distance.
|
||||
pub(crate) fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
|
||||
let mut samples = vec![tip];
|
||||
let mut current = tip;
|
||||
let mut distance = 0_usize;
|
||||
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
|
||||
current = parent;
|
||||
distance += 1;
|
||||
if distance.is_power_of_two() {
|
||||
samples.push(current);
|
||||
}
|
||||
}
|
||||
// Always the root: copies of one document share it however far they diverged, so the answering peer
|
||||
// can tell a divergent copy from a stranger and merge rather than replace.
|
||||
if samples.last() != Some(¤t) {
|
||||
samples.push(current);
|
||||
}
|
||||
samples
|
||||
}
|
||||
|
||||
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
|
||||
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
let known = self.ancestors(known);
|
||||
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
@@ -219,13 +179,6 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record when a retired delta entered history (outside its `Rev`). Returns whether the delta was found.
|
||||
pub(crate) fn set_retired_at(&mut self, rev: Rev, wall_ms: u64) -> bool {
|
||||
let Some(&position) = self.index.get(&rev) else { return false };
|
||||
self.deltas[position].retired_at_ms = wall_ms;
|
||||
true
|
||||
}
|
||||
|
||||
/// Set a local annotation attribute (e.g. a commit message) on a retired delta in place. Excluded
|
||||
/// from the delta's `Rev`, so identity and the index are unchanged. Returns whether the delta was found.
|
||||
pub fn annotate(&mut self, rev: Rev, key: &str, value: Value, timestamp: TimeStamp) -> bool {
|
||||
|
||||
@@ -1,281 +0,0 @@
|
||||
//! What people say about a document's history, kept beside it rather than in it: user names, step labels
|
||||
//! and tags. None of it is folded into the document, so moving the head never changes it and stating it
|
||||
//! never rewrites a delta. Each [`MetadataFact`] carries a wall-clock stamp and the newer of two about the
|
||||
//! same thing wins, so the record merges the same in any order and any number of times. On disk the facts
|
||||
//! are appended one per line and folded on read, so nothing is ever rewritten.
|
||||
|
||||
use crate::ids::{PeerId, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub struct WallStamp {
|
||||
pub ms: u64,
|
||||
pub peer: PeerId,
|
||||
}
|
||||
|
||||
/// What a fact is about.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
pub enum Subject {
|
||||
User(UserId),
|
||||
Rev(Rev),
|
||||
}
|
||||
|
||||
/// One statement: an attribute of a user or of a rev, with its stamp. The unit of the file and of a merge.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MetadataFact {
|
||||
pub subject: Subject,
|
||||
pub key: String,
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// One stated value with its stamp, as the folded record holds it.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Fact {
|
||||
pub value: serde_json::Value,
|
||||
pub stamp: WallStamp,
|
||||
}
|
||||
|
||||
/// Everything on record about one user.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct UserRecord {
|
||||
pub user: UserId,
|
||||
pub attributes: BTreeMap<String, Fact>,
|
||||
}
|
||||
|
||||
/// Everything on record about one rev, which stands for the interaction it closes.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct RevRecord {
|
||||
pub rev: Rev,
|
||||
pub attributes: BTreeMap<String, Fact>,
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a user.
|
||||
pub mod user_attr {
|
||||
/// The display name the user chose. Absent or empty means unnamed.
|
||||
pub const NAME: &str = "name";
|
||||
}
|
||||
|
||||
/// The attribute keys the editor writes for a rev.
|
||||
pub mod rev_attr {
|
||||
/// The name a person gave the interaction the rev closes. Absent or empty means unnamed.
|
||||
pub const LABEL: &str = "label";
|
||||
/// A tag on the rev, one key per tag name after this prefix; `true` while it stands, `false` once removed.
|
||||
pub const TAG_PREFIX: &str = "tag:";
|
||||
}
|
||||
|
||||
/// The folded record. Users and revs are kept sorted so two copies holding the same facts serialize alike.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct HistoryMetadata {
|
||||
#[serde(default)]
|
||||
pub users: Vec<UserRecord>,
|
||||
#[serde(default)]
|
||||
pub revs: Vec<RevRecord>,
|
||||
}
|
||||
|
||||
impl HistoryMetadata {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.users.is_empty() && self.revs.is_empty()
|
||||
}
|
||||
|
||||
/// The record folded from facts in file order: each fact lands unless a newer one about the same thing stands.
|
||||
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
|
||||
let mut record = Self::default();
|
||||
for fact in facts {
|
||||
record.absorb(fact);
|
||||
}
|
||||
record
|
||||
}
|
||||
|
||||
/// Every fact the record holds, users first then revs, for writing it out whole.
|
||||
pub fn facts(&self) -> Vec<MetadataFact> {
|
||||
let users = self.users.iter().flat_map(|record| {
|
||||
record.attributes.iter().map(|(key, fact)| MetadataFact {
|
||||
subject: Subject::User(record.user),
|
||||
key: key.clone(),
|
||||
value: fact.value.clone(),
|
||||
stamp: fact.stamp,
|
||||
})
|
||||
});
|
||||
let revs = self.revs.iter().flat_map(|record| {
|
||||
record.attributes.iter().map(|(key, fact)| MetadataFact {
|
||||
subject: Subject::Rev(record.rev),
|
||||
key: key.clone(),
|
||||
value: fact.value.clone(),
|
||||
stamp: fact.stamp,
|
||||
})
|
||||
});
|
||||
users.chain(revs).collect()
|
||||
}
|
||||
|
||||
pub fn user(&self, user: UserId) -> Option<&UserRecord> {
|
||||
self.users.binary_search_by_key(&user, |record| record.user).ok().map(|index| &self.users[index])
|
||||
}
|
||||
|
||||
pub(crate) fn user_attribute(&self, user: UserId, key: &str) -> Option<&Fact> {
|
||||
self.user(user)?.attributes.get(key)
|
||||
}
|
||||
|
||||
/// The user's display name, if one is on record and not empty.
|
||||
pub fn user_name(&self, user: UserId) -> Option<&str> {
|
||||
self.user_attribute(user, user_attr::NAME)?.value.as_str().filter(|name| !name.is_empty())
|
||||
}
|
||||
|
||||
pub fn rev(&self, rev: Rev) -> Option<&RevRecord> {
|
||||
self.revs.binary_search_by_key(&rev, |record| record.rev).ok().map(|index| &self.revs[index])
|
||||
}
|
||||
|
||||
pub(crate) fn rev_attribute(&self, rev: Rev, key: &str) -> Option<&Fact> {
|
||||
self.rev(rev)?.attributes.get(key)
|
||||
}
|
||||
|
||||
/// The name a person gave the interaction `rev` closes, if any and not empty.
|
||||
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
|
||||
self.rev_attribute(rev, rev_attr::LABEL)?.value.as_str().filter(|label| !label.is_empty())
|
||||
}
|
||||
|
||||
/// The tags standing on `rev`, in name order.
|
||||
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
|
||||
let Some(record) = self.rev(rev) else { return Vec::new() };
|
||||
record
|
||||
.attributes
|
||||
.iter()
|
||||
.filter(|(_, fact)| fact.value == serde_json::Value::Bool(true))
|
||||
.filter_map(|(key, _)| key.strip_prefix(rev_attr::TAG_PREFIX))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// State a fact about a user. A no-op when the same value already stands; otherwise stamped after the fact it
|
||||
/// replaces, so a clock behind a peer's still wins. Returns the fact as stated, for appending and broadcasting.
|
||||
pub fn set_user_attribute(&mut self, user: UserId, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
|
||||
self.state(Subject::User(user), key, value, stamp)
|
||||
}
|
||||
|
||||
/// State a fact about a rev; see [`set_user_attribute`](Self::set_user_attribute).
|
||||
pub fn set_rev_attribute(&mut self, rev: Rev, key: &str, value: serde_json::Value, stamp: WallStamp) -> Option<MetadataFact> {
|
||||
self.state(Subject::Rev(rev), key, value, stamp)
|
||||
}
|
||||
|
||||
fn state(&mut self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
|
||||
let attributes = self.attributes_mut(subject);
|
||||
if let Some(existing) = attributes.get(key) {
|
||||
if existing.value == value {
|
||||
return None;
|
||||
}
|
||||
if stamp <= existing.stamp {
|
||||
stamp.ms = existing.stamp.ms + 1;
|
||||
}
|
||||
}
|
||||
attributes.insert(key.to_string(), Fact { value: value.clone(), stamp });
|
||||
Some(MetadataFact {
|
||||
subject,
|
||||
key: key.to_string(),
|
||||
value,
|
||||
stamp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Take on a fact stated elsewhere unless an equal or newer stamp stands for the same thing. Returns whether
|
||||
/// it landed.
|
||||
pub(crate) fn absorb(&mut self, fact: MetadataFact) -> bool {
|
||||
let attributes = self.attributes_mut(fact.subject);
|
||||
if attributes.get(&fact.key).is_some_and(|mine| fact.stamp <= mine.stamp) {
|
||||
return false;
|
||||
}
|
||||
attributes.insert(fact.key, Fact { value: fact.value, stamp: fact.stamp });
|
||||
true
|
||||
}
|
||||
|
||||
/// Take on another copy's record: for every key, the newer stamp wins. Returns the facts that landed, for
|
||||
/// appending to the file.
|
||||
pub fn merge(&mut self, other: &Self) -> Vec<MetadataFact> {
|
||||
other.facts().into_iter().filter(|fact| self.absorb(fact.clone())).collect()
|
||||
}
|
||||
|
||||
fn attributes_mut(&mut self, subject: Subject) -> &mut BTreeMap<String, Fact> {
|
||||
match subject {
|
||||
Subject::User(user) => {
|
||||
let index = match self.users.binary_search_by_key(&user, |record| record.user) {
|
||||
Ok(index) => index,
|
||||
Err(index) => {
|
||||
self.users.insert(index, UserRecord { user, attributes: BTreeMap::new() });
|
||||
index
|
||||
}
|
||||
};
|
||||
&mut self.users[index].attributes
|
||||
}
|
||||
Subject::Rev(rev) => {
|
||||
let index = match self.revs.binary_search_by_key(&rev, |record| record.rev) {
|
||||
Ok(index) => index,
|
||||
Err(index) => {
|
||||
self.revs.insert(index, RevRecord { rev, attributes: BTreeMap::new() });
|
||||
index
|
||||
}
|
||||
};
|
||||
&mut self.revs[index].attributes
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stamp(ms: u64, peer: u64) -> WallStamp {
|
||||
WallStamp { ms, peer: PeerId(peer) }
|
||||
}
|
||||
|
||||
fn rev(n: u128) -> Rev {
|
||||
Rev::new(n).expect("non-zero")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newer_fact_wins_whatever_order_the_copies_meet_in() {
|
||||
let mut a = HistoryMetadata::default();
|
||||
let mut b = HistoryMetadata::default();
|
||||
assert!(a.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(10, 1)).is_some());
|
||||
assert!(b.set_user_attribute(UserId(1), user_attr::NAME, "Ada L.".into(), stamp(20, 2)).is_some());
|
||||
|
||||
let mut ab = a.clone();
|
||||
assert_eq!(ab.merge(&b).len(), 1);
|
||||
let mut ba = b.clone();
|
||||
assert!(ba.merge(&a).is_empty());
|
||||
assert_eq!(ab, ba);
|
||||
assert_eq!(ab.user_name(UserId(1)), Some("Ada L."));
|
||||
assert!(ab.merge(&b).is_empty(), "merging again changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_behind_a_peers_still_gets_its_say() {
|
||||
let mut record = HistoryMetadata::default();
|
||||
record.set_user_attribute(UserId(1), user_attr::NAME, "Ada".into(), stamp(100, 2));
|
||||
let stated = record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(5, 1)).expect("a change");
|
||||
assert_eq!(stated.stamp.ms, 101);
|
||||
assert_eq!(record.user_name(UserId(1)), Some("Countess"));
|
||||
assert!(
|
||||
record.set_user_attribute(UserId(1), user_attr::NAME, "Countess".into(), stamp(500, 1)).is_none(),
|
||||
"the same value is no change"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fold_of_the_facts_is_the_record_and_back() {
|
||||
let mut record = HistoryMetadata::default();
|
||||
record.set_user_attribute(UserId(9), user_attr::NAME, "".into(), stamp(1, 1));
|
||||
record.set_user_attribute(UserId(3), user_attr::NAME, "Bea".into(), stamp(1, 1));
|
||||
record.set_rev_attribute(rev(7), rev_attr::LABEL, "Fixed the eye".into(), stamp(2, 1));
|
||||
record.set_rev_attribute(rev(7), "tag:v1", true.into(), stamp(3, 1));
|
||||
record.set_rev_attribute(rev(7), "tag:draft", false.into(), stamp(4, 1));
|
||||
assert_eq!(record.user_name(UserId(9)), None);
|
||||
assert_eq!(record.users.iter().map(|record| record.user).collect::<Vec<_>>(), vec![UserId(3), UserId(9)]);
|
||||
assert_eq!(record.rev_label(rev(7)), Some("Fixed the eye"));
|
||||
assert_eq!(record.rev_tags(rev(7)), vec!["v1"]);
|
||||
|
||||
let facts = record.facts();
|
||||
assert_eq!(facts.len(), 5);
|
||||
assert_eq!(HistoryMetadata::fold(facts), record);
|
||||
}
|
||||
}
|
||||
@@ -5,14 +5,12 @@ pub mod crdt;
|
||||
pub mod delta;
|
||||
pub mod document;
|
||||
pub mod history;
|
||||
mod history_metadata;
|
||||
pub mod ids;
|
||||
pub mod model;
|
||||
mod prior;
|
||||
pub mod registry;
|
||||
pub mod resources;
|
||||
pub mod session;
|
||||
pub mod touched;
|
||||
pub mod value;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -26,14 +24,12 @@ pub use attributes::*;
|
||||
pub use crdt::*;
|
||||
pub use document::*;
|
||||
pub use history::History;
|
||||
pub use history_metadata::{Fact, HistoryMetadata, MetadataFact, RevRecord, Subject, UserRecord, WallStamp, rev_attr, user_attr};
|
||||
pub use ids::*;
|
||||
pub use model::*;
|
||||
pub use prior::{NetworkField, NodeField, Prior};
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
pub use touched::Touched;
|
||||
pub use value::{Value, ValueError, from_value, to_value};
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
@@ -44,13 +40,11 @@ pub use from_runtime::{
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
|
||||
pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod crdt;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{Attributes, Implementation, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use crate::{Attributes, Network, NetworkId, Node, NodeId, PeerId, ResourceEntry, ResourceId, ResourceStore, SourceKey, TimeStamp, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -66,31 +66,6 @@ impl Registry {
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry as `to_runtime` renders it: a removed network that a live node still runs counts as present, so a
|
||||
/// diff against the runtime does not take it for an addition.
|
||||
pub(crate) fn as_rendered(&self) -> Registry {
|
||||
let mut rendered = self.clone();
|
||||
for node in self.node_instances.values() {
|
||||
if let Implementation::Network(id) = node.implementation
|
||||
&& let Some(mark) = rendered.removed_networks.remove(&id)
|
||||
{
|
||||
rendered.networks.insert(id, mark.content);
|
||||
}
|
||||
}
|
||||
rendered
|
||||
}
|
||||
|
||||
/// Whether both registries removed the same entities at the same times. The marks decide how future
|
||||
/// ops land, so registries agreeing on values but not on marks will diverge.
|
||||
pub fn removal_marks_equal(&self, other: &Self) -> bool {
|
||||
fn same<K: std::hash::Hash + Eq, T>(a: &HashMap<K, Tombstone<T>>, b: &HashMap<K, Tombstone<T>>) -> bool {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.all(|(id, mark)| b.get(id).is_some_and(|other| other.timestamp == mark.timestamp && other.placeholder == mark.placeholder))
|
||||
}
|
||||
same(&self.removed_nodes, &other.removed_nodes) && same(&self.removed_networks, &other.removed_networks) && same(&self.removed_resources, &other.removed_resources)
|
||||
}
|
||||
|
||||
/// True if both registries agree on every value-bearing field, ignoring per-slot and
|
||||
/// per-attribute timestamps. Mirrors `compute_deltas`'s value-only semantics, so unchanged
|
||||
/// state at a stamped slot doesn't count as drift. `peer_users` is excluded: it isn't diffed by
|
||||
|
||||
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{
|
||||
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId,
|
||||
Value, to_value,
|
||||
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value,
|
||||
to_value,
|
||||
};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -19,9 +19,6 @@ pub struct Session {
|
||||
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
|
||||
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
|
||||
remote_tips: HashMap<PeerId, Rev>,
|
||||
/// The registry the runtime was last built from or staged to. Local diffs are taken against it,
|
||||
/// so edits peers applied to the working registry in the meantime are not diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -43,7 +40,6 @@ impl Session {
|
||||
Self {
|
||||
document: Document::empty(peer, user),
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,22 +51,11 @@ impl Session {
|
||||
self.document.user
|
||||
}
|
||||
|
||||
/// Change the person behind this peer. The next staged batch registers the peer again, and the newer
|
||||
/// registration wins everywhere.
|
||||
pub fn set_user(&mut self, user: UserId) {
|
||||
self.document.user = user;
|
||||
}
|
||||
|
||||
pub fn user_of(&self, peer: PeerId) -> Option<UserId> {
|
||||
let registered = || self.document.working_registry.peer_users.get(&peer).map(|registration| registration.user);
|
||||
(peer == self.document.peer).then_some(self.document.user).or_else(registered)
|
||||
}
|
||||
|
||||
/// Whether `peer` is this person: this device, or another registered to the same user.
|
||||
pub fn is_mine(&self, peer: PeerId) -> bool {
|
||||
self.user_of(peer) == Some(self.document.user)
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
&self.document.working_registry
|
||||
}
|
||||
@@ -97,28 +82,11 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let rendered;
|
||||
let base = match &self.runtime_base {
|
||||
Some(base) => base,
|
||||
None => {
|
||||
rendered = self.document.working_registry.as_rendered();
|
||||
&rendered
|
||||
}
|
||||
};
|
||||
let ops = crate::delta::compute_deltas(base, &conversion.registry);
|
||||
|
||||
// The base moves only once the ops are staged, so a failure leaves the next diff covering them. Lenient, as the
|
||||
// diff is against what the runtime held: a peer's concurrent write may have reshaped what it names.
|
||||
let hot_ops = self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Idempotent)?;
|
||||
self.runtime_base = Some(conversion.registry.clone());
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// Record that the runtime now reflects the working registry, after the caller rebuilt it from there.
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.as_rendered());
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||
/// caller can key per-network, per-peer view state (`session.json`) by a stable id. Derived from the
|
||||
/// network structure alone; resources/declarations are irrelevant to the ids.
|
||||
@@ -179,11 +147,11 @@ impl Session {
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub(crate) fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())), ApplyMode::Strict)
|
||||
self.stage_ops_with(ops.into_iter().map(|op| (op, Attributes::new())))
|
||||
}
|
||||
|
||||
/// [`stage_ops`](Self::stage_ops), each op carrying its hot op's attributes. A batch is staged whole or not at all.
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>, mode: ApplyMode) -> Result<Vec<HotOp>, CrdtError> {
|
||||
fn stage_ops_with(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Attributes)>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
// A batch is staged whole or not at all.
|
||||
let mut pending: Vec<(RegistryDelta, Attributes)> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -209,7 +177,7 @@ impl Session {
|
||||
sequence,
|
||||
attributes,
|
||||
};
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), mode) {
|
||||
if let Err(error) = self.document.stage_hot_op(hot_op.clone(), ApplyMode::Strict) {
|
||||
// The run continues where it was, so no sequence goes unused.
|
||||
self.document.last_hot_sequence = sequence_before;
|
||||
if !staged.is_empty() {
|
||||
@@ -223,22 +191,9 @@ impl Session {
|
||||
self.document.last_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
self.advance_runtime_base(&staged);
|
||||
Ok(staged)
|
||||
}
|
||||
|
||||
/// A local batch is an edit the runtime already shows, so the base a whole-document stage diffs against moves
|
||||
/// with it; otherwise that stage would restate the batch, which fails on what the batch added.
|
||||
fn advance_runtime_base(&mut self, staged: &[HotOp]) {
|
||||
let Some(base) = self.runtime_base.take() else { return };
|
||||
let working = std::mem::replace(&mut self.document.working_registry, base);
|
||||
for hot_op in staged {
|
||||
// Lenient, like replaying an op already seen: the base held what the runtime held when the batch was made.
|
||||
let _ = self.document.apply_op_with(RegistryTarget::Working, hot_op.op.clone(), hot_op.timestamp, ApplyMode::Idempotent);
|
||||
}
|
||||
self.runtime_base = Some(std::mem::replace(&mut self.document.working_registry, working));
|
||||
}
|
||||
|
||||
/// Wrap each op as a `Delta`, apply it, and chain it onto the local history. One tick per op.
|
||||
///
|
||||
/// Operates on the retired snapshot, so each `reverse` holds the true pre-op state; the working registry already
|
||||
@@ -251,7 +206,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops paired with their authored stamp (`None` to mint one), which retirement keeps
|
||||
/// so LWW resolves as it did live; a coarsened delta passes the newest it fuses.
|
||||
/// so LWW resolves as it did live.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Retired;
|
||||
let ops = ops.into_iter();
|
||||
@@ -312,7 +267,6 @@ impl Session {
|
||||
..Document::empty(peer, user)
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,231 +288,14 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Drop hot ops another peer has retired, without retiring them locally. The working registry is rebuilt
|
||||
/// without them, so until their deltas arrive it shows the snapshot plus what is still hot.
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.mark_retired(retired.iter().copied())
|
||||
}
|
||||
|
||||
/// Take back this peer's latest interaction (its ops since the previous marker) while it is still hot, so an
|
||||
/// accidental gesture and its undo leave no step in history. `None` when nothing is hot or the interaction
|
||||
/// already retired somewhere this peer knows of, which makes it an undo of a retired step.
|
||||
pub fn retract_interaction(&mut self) -> Result<Option<Retraction>, CrdtError> {
|
||||
let peer = self.document.peer;
|
||||
let mut own: Vec<&HotOp> = self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp.peer == peer).collect();
|
||||
own.sort_by_key(|hot_op| hot_op.sequence);
|
||||
// The latest interaction: everything after the previous marker, through a trailing marker if any.
|
||||
let closed_before = match own.last() {
|
||||
Some(last) if last.ends_interaction() => own.len() - 1,
|
||||
Some(_) => own.len(),
|
||||
None => return Ok(None),
|
||||
};
|
||||
let start = own[..closed_before].iter().rposition(|hot_op| hot_op.ends_interaction()).map_or(0, |position| position + 1);
|
||||
if own[start..].iter().all(|hot_op| matches!(hot_op.op, RegistryDelta::Meta)) {
|
||||
return Ok(None);
|
||||
}
|
||||
let ids: Vec<HotOpId> = own[start..].iter().map(|hot_op| hot_op.id()).collect();
|
||||
if ids.iter().any(|&id| self.document.retired.covers(id)) {
|
||||
return Ok(None);
|
||||
}
|
||||
self.runtime_base = None;
|
||||
let (touched, taken) = self.document.retract_hot_ops(&ids);
|
||||
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
|
||||
Ok(Some(Retraction { ids, touched, ops }))
|
||||
}
|
||||
|
||||
/// Take back hot ops another peer retracted. See [`retract_interaction`](Self::retract_interaction).
|
||||
pub fn retract_hot_ops(&mut self, ids: &[HotOpId]) -> Touched {
|
||||
self.runtime_base = None;
|
||||
self.document.retract_hot_ops(ids).0
|
||||
}
|
||||
|
||||
/// The last delta of this person's latest retired interaction on the line, if any: what an undo of a
|
||||
/// retired step in a session names. Any peer of the same user counts; see [`is_mine`](Self::is_mine).
|
||||
pub fn latest_own_interaction(&self) -> Option<Rev> {
|
||||
let mut current = self.document.head?;
|
||||
loop {
|
||||
let delta = self.document.history.get(current)?;
|
||||
if delta.is_interaction_end() && self.is_mine(delta.author) {
|
||||
return Some(current);
|
||||
}
|
||||
current = delta.parent?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo a retired interaction in a session by dropping it out of the shared line: the head moves to its parent
|
||||
/// and the later steps are minted again there with the same author, stamp and kind, so every follower holds
|
||||
/// identical revs; the originals stay as an abandoned branch. Returns the move to broadcast and what the
|
||||
/// dropped ops named. Only the retirer does this; a guest asks it to.
|
||||
pub fn drop_interaction(&mut self, undone: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
let base = self.interaction_start_parent(undone, false).ok_or(CrdtError::NotUndoable(undone))?;
|
||||
|
||||
// The line from the head down to the interaction's parent, newest first.
|
||||
let mut walked = Vec::new();
|
||||
let mut current = from;
|
||||
while current != Some(base) {
|
||||
let rev = current.ok_or(CrdtError::NotFoundInHistory(undone))?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
|
||||
return Err(CrdtError::NotUndoable(undone));
|
||||
}
|
||||
current = delta.parent;
|
||||
walked.push(delta);
|
||||
}
|
||||
let position = walked.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
|
||||
|
||||
// Fold from history at the new head.
|
||||
self.document.head = Some(base);
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
|
||||
let mut touched = Touched::default();
|
||||
walked[position..].iter().for_each(|delta| touched.record(&delta.kind));
|
||||
let mut copies = Vec::new();
|
||||
for original in walked[..position].iter().rev() {
|
||||
let revs = self.commit_ops_authored_at([(original.kind.clone(), Some(original.timestamp))], true)?;
|
||||
// A copy keeps what was said about the original: its interaction end, and when it was retired.
|
||||
if let Some(&rev) = revs.last() {
|
||||
self.carry_attributes(original, rev);
|
||||
}
|
||||
copies.extend(revs.iter().filter_map(|&rev| self.document.history.get(rev).cloned()));
|
||||
}
|
||||
// Two branches now, so restore the canonical file order every peer computes alike.
|
||||
self.document.history.canonical_sort();
|
||||
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
head: self.document.head,
|
||||
copies,
|
||||
},
|
||||
touched,
|
||||
))
|
||||
}
|
||||
|
||||
/// Move the shared head back to an ancestor in a session. The line down to `target` stays as an abandoned
|
||||
/// branch, nothing is minted, and the snapshot refolds at the target as in [`drop_interaction`](Self::drop_interaction).
|
||||
/// Returns the move to broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to.
|
||||
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
|
||||
let from = self.document.head;
|
||||
if from == Some(target) {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let mut touched = Touched::default();
|
||||
let mut current = from;
|
||||
while current != Some(target) {
|
||||
let rev = current.ok_or(CrdtError::NotFoundInHistory(target))?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?;
|
||||
touched.record(&delta.kind);
|
||||
current = delta.parent;
|
||||
}
|
||||
self.document.head = Some(target);
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.redo_stack.clear();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok((
|
||||
HeadMove {
|
||||
from,
|
||||
head: Some(target),
|
||||
copies: Vec::new(),
|
||||
},
|
||||
touched,
|
||||
))
|
||||
}
|
||||
|
||||
/// Follow another peer's cursor move: refold the snapshot to where the copies start, take the copies on,
|
||||
/// and put the head where the mover put it. Returns what the walked-over ops named. The move only
|
||||
/// applies from the head it started at; anywhere else this peer has diverged and needs a resync.
|
||||
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
|
||||
if self.document.head != moved.from {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
expected: moved.from,
|
||||
found: self.document.head,
|
||||
});
|
||||
}
|
||||
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
|
||||
|
||||
let mut touched = Touched::default();
|
||||
let mut current = self.document.head;
|
||||
while current != base {
|
||||
let rev = current.ok_or(CrdtError::NothingToUndo)?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?;
|
||||
touched.record(&delta.kind);
|
||||
current = delta.parent;
|
||||
}
|
||||
// Fold from history at the new base, as `drop_interaction` does.
|
||||
self.document.head = base;
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
|
||||
for copy in &moved.copies {
|
||||
if let Some(parent) = copy.parent
|
||||
&& !self.document.history.contains(parent)
|
||||
{
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
self.document.apply_op_with(RegistryTarget::Retired, copy.kind.clone(), copy.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.history.push(copy.clone());
|
||||
self.document.head = Some(copy.id);
|
||||
}
|
||||
if self.document.head != moved.head {
|
||||
return Err(CrdtError::CursorMismatch {
|
||||
expected: moved.head,
|
||||
found: self.document.head,
|
||||
});
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(touched)
|
||||
}
|
||||
|
||||
/// Redo a dropped interaction in a session: mint its ops again on top of the line, as one interaction.
|
||||
/// Its writes carry their original stamps, so a field someone wrote since keeps the newer value.
|
||||
/// Returns the new revs, for an ordinary retirement-style broadcast.
|
||||
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
|
||||
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
|
||||
let mut originals = Vec::new();
|
||||
let mut current = Some(dropped);
|
||||
while current != Some(base) {
|
||||
let rev = current.ok_or(CrdtError::NothingToRedo)?;
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
current = delta.parent;
|
||||
originals.push(delta);
|
||||
}
|
||||
originals.reverse();
|
||||
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
|
||||
// The copies keep the originals' attributes and retirement times.
|
||||
if revs.len() == originals.len() {
|
||||
for (original, &rev) in originals.iter().zip(&revs) {
|
||||
self.carry_attributes(original, rev);
|
||||
}
|
||||
}
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
|
||||
pub fn retired_marks(&self) -> &RetiredMarks {
|
||||
&self.document.retired
|
||||
}
|
||||
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
|
||||
let touched = self.document.absorb_retired_marks(remote);
|
||||
if !touched.is_empty() {
|
||||
self.runtime_base = None;
|
||||
}
|
||||
touched
|
||||
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
|
||||
self.document.absorb_retired_marks(remote);
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -567,6 +304,38 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
absorbed.push(delta);
|
||||
}
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
@@ -581,173 +350,6 @@ impl Session {
|
||||
self.document.history.len()
|
||||
}
|
||||
|
||||
/// Take a retirer's deltas on and put the head where the retirer's is, minting nothing: a guest follows the
|
||||
/// host's line rather than merging with it. A batch not extending this head (the host moved the line) refolds
|
||||
/// the snapshot, leaving the old tip as an abandoned branch. `head` defaults to the batch's last delta.
|
||||
pub fn follow(&mut self, incoming: Vec<Delta>, head: Option<Rev>) -> Result<MergeOutcome, CrdtError> {
|
||||
let before = self.document.head;
|
||||
let length_before = self.document.history.len();
|
||||
let named = head.is_some();
|
||||
let head = head.or_else(|| incoming.last().map(|delta| delta.id)).or(before);
|
||||
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(parent) = delta.all_parents().find(|&parent| !self.document.history.contains(parent)) {
|
||||
return Err(CrdtError::NotFoundInHistory(parent));
|
||||
}
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
// A batch bringing nothing new whose end this head already descends from is a late copy of a line followed
|
||||
// past; only a named head or a head move takes the line back. One ending ahead, like a restored step, still moves it.
|
||||
let stale = |head: Rev| !named && before.is_some_and(|before| self.document.history.is_ancestor(head, before));
|
||||
if self.document.history.len() == length_before && (head == before || head.is_some_and(stale)) {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
// The new head extends this one when walking its parents back over the batch reaches this head.
|
||||
let mut chain = Vec::new();
|
||||
let mut current = head;
|
||||
let extends = loop {
|
||||
if current == before {
|
||||
break true;
|
||||
}
|
||||
let Some(rev) = current else { break false };
|
||||
let Some(delta) = self.document.history.get(rev) else { break false };
|
||||
if self.document.history.position(rev).is_some_and(|position| position < length_before) {
|
||||
break false;
|
||||
}
|
||||
// A merge joins a line this chain does not walk, possibly a branch this peer abandoned, so the
|
||||
// snapshot has to be folded from the new head's whole ancestry.
|
||||
if delta.all_parents().count() > 1 {
|
||||
break false;
|
||||
}
|
||||
chain.push(delta.clone());
|
||||
current = delta.parent;
|
||||
};
|
||||
|
||||
if extends {
|
||||
for delta in chain.iter().rev() {
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
}
|
||||
self.document.head = head;
|
||||
} else {
|
||||
self.document.head = head;
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
if !self.document.history.extends_canonically(length_before) {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
Ok(head.map_or(MergeOutcome::NoOp, MergeOutcome::FastForward))
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
|
||||
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
|
||||
/// incoming tips with a [`RegistryDelta::Merge`].
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
|
||||
let length_before = self.document.history.len();
|
||||
let head_before = self.document.head;
|
||||
|
||||
// Working is snapshot plus hot tail, so each delta lands on both (cloning would promote hot ops). Every
|
||||
// field, presence included, is last-writer-wins, so the batch's order decides nothing.
|
||||
let mut absorbed_ids = HashSet::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
absorbed_ids.insert(delta.id);
|
||||
self.document.history.push(delta);
|
||||
}
|
||||
if absorbed_ids.is_empty() {
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
// A batch chaining off the last delta, as a retirement's does, is already in canonical order. The
|
||||
// order matters to the history file and `Rev` determinism only, not to the registries.
|
||||
let extends = self.document.history.extends_canonically(length_before);
|
||||
if !extends {
|
||||
self.document.history.canonical_sort();
|
||||
}
|
||||
|
||||
let history = &self.document.history;
|
||||
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
|
||||
let parents: Vec<Rev> = if extends && self.document.head == last_before {
|
||||
// The chain hangs off `head`, so `head` is its ancestor and the chain's end is the one tip.
|
||||
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
|
||||
} else {
|
||||
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
|
||||
candidates.extend(self.document.head);
|
||||
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
|
||||
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
|
||||
};
|
||||
|
||||
let outcome = match parents.as_slice() {
|
||||
[tip] => MergeOutcome::FastForward(*tip),
|
||||
_ => {
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(parents, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
|
||||
self.document.history.push(merge);
|
||||
MergeOutcome::Merged(merge_rev)
|
||||
}
|
||||
};
|
||||
self.document.head = outcome.head();
|
||||
// The line moved, so what was undone is either on it now or left behind. A peer holds what came from it, so the
|
||||
// line up to here is published and a silent undo leaves it be.
|
||||
self.document.redo_stack.clear();
|
||||
if let Some(head) = self.document.head {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
|
||||
// A merge may join a branch this peer abandoned, whose effects applying the batch did not bring into
|
||||
// the snapshot, and so may a batch sorted in ahead of the tail. Either way, refold from the new head.
|
||||
let mut refold = !extends || matches!(outcome, MergeOutcome::Merged(_));
|
||||
if !refold && let MergeOutcome::FastForward(tip) = outcome {
|
||||
refold = !self.fold_in_skipped(tip, head_before, &absorbed_ids)?;
|
||||
}
|
||||
if refold {
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
self.document.rebuild_working();
|
||||
self.runtime_base = None;
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// Fold in the deltas between `from` and the new `tip` that the batch did not bring: steps undone here that the
|
||||
/// incoming line builds on. Walks first parents, so O(the batch plus those steps). `false` when the walk meets a
|
||||
/// merge or misses `from`, for the caller to refold instead.
|
||||
fn fold_in_skipped(&mut self, tip: Rev, from: Option<Rev>, absorbed: &HashSet<Rev>) -> Result<bool, CrdtError> {
|
||||
let mut skipped = Vec::new();
|
||||
let mut current = Some(tip);
|
||||
while current != from {
|
||||
let Some(delta) = current.and_then(|rev| self.document.history.get(rev)) else { return Ok(false) };
|
||||
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
|
||||
return Ok(false);
|
||||
}
|
||||
if !absorbed.contains(&delta.id) {
|
||||
skipped.push(delta.clone());
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
for delta in skipped.into_iter().rev() {
|
||||
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
self.document.apply_op_idempotent(delta.kind, delta.timestamp)?;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
|
||||
/// re-registration possibly before the marker; empty when nothing is open.
|
||||
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
|
||||
@@ -764,7 +366,7 @@ impl Session {
|
||||
}
|
||||
let mut closing = Attributes::new();
|
||||
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
|
||||
self.stage_ops_with([(RegistryDelta::Meta, closing)])
|
||||
}
|
||||
|
||||
/// Every author's closed interactions in the hot log, the earliest closed first.
|
||||
@@ -802,16 +404,6 @@ impl Session {
|
||||
closed
|
||||
}
|
||||
|
||||
/// Retire one closed interaction coarsened, marking its last delta as the interaction's end. Every op is
|
||||
/// retired, the ones coarsening drops included. Returns the new revs.
|
||||
pub fn retire_interaction(&mut self, interaction: &ClosedInteraction) -> Result<Vec<Rev>, CrdtError> {
|
||||
let revs = self.retire_hot_ops_with(&interaction.ops, true)?;
|
||||
if let Some(&last) = revs.last() {
|
||||
self.mark_interaction_end(last);
|
||||
}
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
@@ -819,20 +411,14 @@ impl Session {
|
||||
|
||||
/// Promote the given hot ops into retired deltas in hot-log order, each keeping its authored stamp.
|
||||
///
|
||||
/// One retired delta per hot op, except a `Meta` op, which commits nothing. [`retire_interaction`](Self::retire_interaction)
|
||||
/// coarsens a closed interaction instead.
|
||||
/// One retired delta per hot op, except a `Meta` op, which commits nothing.
|
||||
pub fn retire_hot_ops(&mut self, ids: &[HotOpId]) -> Result<Vec<Rev>, CrdtError> {
|
||||
self.retire_hot_ops_with(ids, false)
|
||||
}
|
||||
|
||||
fn retire_hot_ops_with(&mut self, ids: &[HotOpId], coarsened: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let wanted: HashSet<HotOpId> = ids.iter().copied().collect();
|
||||
let (drained, kept): (Vec<HotOp>, Vec<HotOp>) = self.document.hot_log.drain(..).partition(|hot_op| wanted.contains(&hot_op.id()));
|
||||
self.document.hot_log = kept;
|
||||
self.document.resync_hot_timestamps();
|
||||
self.document.retired.extend(drained.iter().map(HotOp::id));
|
||||
|
||||
let drained = if coarsened { coarsen(drained) } else { drained };
|
||||
let ops = drained
|
||||
.into_iter()
|
||||
.filter(|hot_op| !matches!(hot_op.op, RegistryDelta::Meta))
|
||||
@@ -840,9 +426,7 @@ impl Session {
|
||||
self.commit_ops_authored_at(ops, true)
|
||||
}
|
||||
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author and whether or not its
|
||||
/// interaction is closed. For callers that own the whole log, tests mostly; a session retires by
|
||||
/// [`retire_interaction`](Self::retire_interaction).
|
||||
/// Promote every hot op stamped at or before `up_to`, whatever its author.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
let ids = self.hot_ops_up_to(up_to);
|
||||
self.retire_hot_ops(&ids)
|
||||
@@ -854,25 +438,6 @@ impl Session {
|
||||
self.document.history.mark_interaction_end(rev, timestamp);
|
||||
}
|
||||
|
||||
/// Record when these retired deltas entered history, in wall-clock milliseconds as the retirer saw them.
|
||||
/// Outside their revs, and never used for ordering.
|
||||
pub fn stamp_retired_at(&mut self, revs: &[Rev], wall_ms: u64) {
|
||||
for &rev in revs {
|
||||
self.document.history.set_retired_at(rev, wall_ms);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give a minted copy every attribute of the delta it stands for, each with the stamp it had, and when the
|
||||
/// original was retired.
|
||||
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
|
||||
if let Some(wall_ms) = original.retired_at() {
|
||||
self.document.history.set_retired_at(copy, wall_ms);
|
||||
}
|
||||
for (key, value) in original.attributes.live() {
|
||||
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
|
||||
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
|
||||
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
|
||||
@@ -918,8 +483,6 @@ impl Session {
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
let base = self.interaction_start_parent(checkpoint, true).ok_or(CrdtError::NothingToUndo)?;
|
||||
// The caller rebuilds the runtime from the rewound registry; until then diff against it directly.
|
||||
self.runtime_base = None;
|
||||
|
||||
while let Some(rev) = self.document.head.filter(|&rev| rev != base) {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
@@ -940,7 +503,6 @@ impl Session {
|
||||
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
|
||||
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
let mut forward = Vec::new();
|
||||
let mut cursor = Some(checkpoint);
|
||||
@@ -983,33 +545,6 @@ impl Session {
|
||||
self.document.history.iter()
|
||||
}
|
||||
|
||||
/// Revs sampled at exponentially growing distances behind `head`, for a remote peer to locate what
|
||||
/// this session is missing.
|
||||
pub fn known_revs(&self) -> Vec<Rev> {
|
||||
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Retired deltas on `head`'s ancestry that are not reachable from `known`, in replay order. An abandoned
|
||||
/// branch stays local: it is this peer's to redo, and a peer that merged it would bring the undone step
|
||||
/// back. Merging thus joins heads, never every tip.
|
||||
///
|
||||
/// What a peer receives it holds, so the head counts as published from then on and a silent undo leaves it be.
|
||||
pub fn deltas_unknown_to(&mut self, known: impl IntoIterator<Item = Rev>) -> Vec<Delta> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
let deltas: Vec<Delta> = self
|
||||
.document
|
||||
.history
|
||||
.deltas_unknown_to(known)
|
||||
.into_iter()
|
||||
.filter(|delta| reachable.contains(&delta.id))
|
||||
.cloned()
|
||||
.collect();
|
||||
if let Some(head) = self.document.head.filter(|_| !deltas.is_empty()) {
|
||||
self.publish_up_to(head);
|
||||
}
|
||||
deltas
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -1147,23 +682,6 @@ impl Default for Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MergeOutcome {
|
||||
NoOp,
|
||||
FastForward(Rev),
|
||||
Merged(Rev),
|
||||
}
|
||||
|
||||
impl MergeOutcome {
|
||||
/// The head after the merge, or `None` when nothing changed.
|
||||
pub fn head(self) -> Option<Rev> {
|
||||
match self {
|
||||
Self::NoOp => None,
|
||||
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
|
||||
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
@@ -1178,7 +696,6 @@ pub struct HotOp {
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Whether the op closes its author's interaction.
|
||||
pub fn ends_interaction(&self) -> bool {
|
||||
self.attributes.get_or(crate::attr::delta::INTERACTION_END, false)
|
||||
}
|
||||
@@ -1226,8 +743,8 @@ pub struct HotOpId {
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops are done with, retired or taken back by their author: each author's gap-free prefix, plus runs past it
|
||||
/// while ops are in flight. Replicated and persisted, so a late copy of a retired op is dropped wherever it lands.
|
||||
/// Which hot ops are retired: each author's gap-free prefix, plus runs past it while ops are in flight. Persisted, so
|
||||
/// a late copy of a retired op is dropped.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RetiredMarks {
|
||||
pub retired_up_to: HashMap<PeerId, HotSequence>,
|
||||
@@ -1248,7 +765,7 @@ fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
}
|
||||
|
||||
impl RetiredMarks {
|
||||
/// Whether this hot op is done with.
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through)
|
||||
|| self
|
||||
@@ -1317,10 +834,6 @@ pub enum CrdtError {
|
||||
NothingToUndo,
|
||||
#[error("Nothing to redo")]
|
||||
NothingToRedo,
|
||||
#[error("Interaction {0} cannot be dropped: it is the base or spans a merge")]
|
||||
NotUndoable(Rev),
|
||||
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
|
||||
CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
|
||||
#[error("Node {0} already exists")]
|
||||
NodeAlreadyExists(NodeId),
|
||||
#[error("Network {0} already exists")]
|
||||
@@ -1328,106 +841,3 @@ pub enum CrdtError {
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
|
||||
/// Which field of the registry a write lands on, for coarsening.
|
||||
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||
enum FieldKey {
|
||||
NodeInput(NodeId, u32),
|
||||
NodeInputAttribute(NodeId, u32, String),
|
||||
NodeAttribute(NodeId, String),
|
||||
NodeImplementation(NodeId),
|
||||
NodeInputs(NodeId),
|
||||
NetworkExport(NetworkId, u32),
|
||||
NetworkAttribute(NetworkId, String),
|
||||
ResourceHash(ResourceId),
|
||||
Source(ResourceId, crate::SourceKey),
|
||||
DocumentAttribute(String),
|
||||
}
|
||||
|
||||
/// The field a write lands on, `None` for an op that is not a plain field write.
|
||||
fn field_of(op: &RegistryDelta) -> Option<FieldKey> {
|
||||
Some(match op {
|
||||
RegistryDelta::ChangeNodeInput { id, index, .. } => FieldKey::NodeInput(*id, *index),
|
||||
RegistryDelta::ChangeNodeInputAttribute { id, index, delta } => FieldKey::NodeInputAttribute(*id, *index, delta.key.clone()),
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => FieldKey::NodeAttribute(*id, delta.key.clone()),
|
||||
RegistryDelta::SetNodeImplementation { id, .. } => FieldKey::NodeImplementation(*id),
|
||||
RegistryDelta::SetNodeInputs { id, .. } => FieldKey::NodeInputs(*id),
|
||||
RegistryDelta::SetNetworkExport { id, index, .. } => FieldKey::NetworkExport(*id, *index),
|
||||
RegistryDelta::ChangeNetworkAttribute { id, delta } => FieldKey::NetworkAttribute(*id, delta.key.clone()),
|
||||
RegistryDelta::SetResourceHash { id, .. } => FieldKey::ResourceHash(*id),
|
||||
RegistryDelta::AddSource { id, key, .. } | RegistryDelta::RemoveSource { id, key } => FieldKey::Source(*id, *key),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => FieldKey::DocumentAttribute(delta.key.clone()),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What a write refers to beyond its own field: a node an input is wired to, or a network an
|
||||
/// implementation points at. A reference is evidence the target exists at the write's stamp, so a write
|
||||
/// that carries one only drops when the write superseding it carries the same.
|
||||
fn references_of(op: &RegistryDelta) -> Vec<u64> {
|
||||
let of_input = |input: &crate::NodeInput| match input {
|
||||
crate::NodeInput::Node { id, .. } => Some(id.0),
|
||||
_ => None,
|
||||
};
|
||||
match op {
|
||||
RegistryDelta::ChangeNodeInput { new_input, .. } => of_input(new_input).into_iter().collect(),
|
||||
RegistryDelta::SetNodeInputs { inputs, .. } => inputs.iter().filter_map(|slot| of_input(&slot.input)).collect(),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => export.as_ref().and_then(of_input).into_iter().collect(),
|
||||
RegistryDelta::SetNodeImplementation {
|
||||
implementation: Implementation::Network(network),
|
||||
..
|
||||
} => vec![network.0],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Coarsens one interaction's ops: a field write that a later write in it supersedes has no effect on the fold
|
||||
/// and is dropped, unless it refers to something the later write does not. A whole-list input write
|
||||
/// supersedes every earlier input write on its node. Structural ops stay.
|
||||
fn coarsen(mut ops: Vec<HotOp>) -> Vec<HotOp> {
|
||||
// Newest by stamp, which is the author's order. The hot log holds arrival order, and a re-announcement
|
||||
// after a lapsed link delivers later ops first, so log order would retire a value the registry never showed.
|
||||
ops.sort_by_key(|hot_op| hot_op.timestamp);
|
||||
let mut keep = vec![true; ops.len()];
|
||||
let mut latest: HashMap<FieldKey, usize> = HashMap::new();
|
||||
for (index, hot_op) in ops.iter().enumerate() {
|
||||
let Some(field) = field_of(&hot_op.op) else { continue };
|
||||
let references = references_of(&hot_op.op);
|
||||
let supersedes = |earlier: &HotOp| references_of(&earlier.op).iter().all(|reference| references.contains(reference));
|
||||
|
||||
if let FieldKey::NodeInputs(id) = field {
|
||||
latest.retain(|key, &mut earlier| {
|
||||
let same_node = matches!(key, FieldKey::NodeInput(node, _) | FieldKey::NodeInputAttribute(node, _, _) | FieldKey::NodeInputs(node) if *node == id);
|
||||
let superseded = same_node && supersedes(&ops[earlier]);
|
||||
keep[earlier] &= !superseded;
|
||||
!superseded
|
||||
});
|
||||
} else if let Some(&earlier) = latest.get(&field)
|
||||
&& supersedes(&ops[earlier])
|
||||
{
|
||||
keep[earlier] = false;
|
||||
}
|
||||
latest.insert(field, index);
|
||||
}
|
||||
ops.into_iter().zip(keep).filter_map(|(hot_op, keep)| keep.then_some(hot_op)).collect()
|
||||
}
|
||||
|
||||
/// What [`Session::retract_interaction`] took back.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Retraction {
|
||||
/// The ids to send, so every peer drops the same ops.
|
||||
pub ids: Vec<HotOpId>,
|
||||
/// What the ops named, for a mirror to bring back into line.
|
||||
pub touched: Touched,
|
||||
/// The ops themselves, marker aside, for a redo to stage afresh.
|
||||
pub ops: Vec<RegistryDelta>,
|
||||
}
|
||||
|
||||
/// A shared cursor move, as [`Session::drop_interaction`] produces it and [`Session::apply_head_move`]
|
||||
/// follows it: the head it started from, the head it ends at, and the steps minted again in between.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HeadMove {
|
||||
pub from: Option<Rev>,
|
||||
pub head: Option<Rev>,
|
||||
pub copies: Vec<Delta>,
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, ResourceId, Session, UserId, Value};
|
||||
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
|
||||
|
||||
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -9,19 +9,13 @@ pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn add_network(id: u64) -> RegistryDelta {
|
||||
fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork {
|
||||
id: NetworkId(id),
|
||||
network: Network::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `hot_op` flagged as the end of its author's interaction, as a peer's `end_interaction` stages it.
|
||||
fn closing(mut hot_op: crate::HotOp) -> crate::HotOp {
|
||||
hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN);
|
||||
hot_op
|
||||
}
|
||||
|
||||
/// Every op commutes, so the snapshot folds to the working registry's values whatever the log order.
|
||||
#[test]
|
||||
fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
@@ -49,234 +43,6 @@ fn retirement_takes_the_ops_under_the_cutoff_in_any_applied_order() {
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// Only closed interactions retire: an author's ops past its last marker stay hot however old, while a
|
||||
/// later interaction from someone else retires around them.
|
||||
#[test]
|
||||
fn only_closed_interactions_retire_and_an_open_one_stays_hot() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open");
|
||||
|
||||
// The guest opens an interaction and leaves it open, stamped earlier than everything the host does.
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
|
||||
|
||||
host.stage_ops([set_attribute("host", 1)]).expect("host op");
|
||||
let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open");
|
||||
assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction());
|
||||
assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}");
|
||||
assert_eq!(closed[0].author, PeerId(1));
|
||||
assert!(closed[0].contiguous);
|
||||
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
|
||||
|
||||
let revs = host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert_eq!(revs.len(), 2, "the marker commits no delta");
|
||||
assert!(
|
||||
host.history().any(|delta| delta.id == revs[1] && delta.is_interaction_end()),
|
||||
"the interaction retires as one undo step"
|
||||
);
|
||||
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
|
||||
assert!(host.hot_log().iter().all(|hot_op| hot_op.timestamp.peer == PeerId(2)));
|
||||
assert!(!host.retired_registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(host.registry().networks.contains_key(&NetworkId(9)));
|
||||
|
||||
// The guest closes: its interaction retires after the host's although it is stamped before it.
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].author, PeerId(2));
|
||||
host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.registry().value_equal(host.retired_registry()));
|
||||
}
|
||||
|
||||
/// An interaction with a gap in its author's run is listed as not contiguous, so the retirer can wait for
|
||||
/// the re-announcement, and closes normally once the gap fills.
|
||||
#[test]
|
||||
fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight");
|
||||
host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 2);
|
||||
assert!(!closed[0].contiguous);
|
||||
assert!(!closed[1].contiguous, "the gap is behind the later interaction too");
|
||||
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
|
||||
let closed = host.closed_interactions();
|
||||
assert!(closed.iter().all(|interaction| interaction.contiguous));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
/// Retracting a hot interaction removes its ops for good and re-derives what they touched from the snapshot
|
||||
/// and the other hot ops, so a concurrent write to the same entity survives. The ops never retire, and a late copy is dropped.
|
||||
#[test]
|
||||
fn a_retracted_interaction_leaves_no_trace_and_keeps_what_others_wrote() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(3)).expect("base");
|
||||
host.document.working_registry = host.document.retired_snapshot.clone();
|
||||
|
||||
// A guest's write to the network and the host's own gesture on the same network, interleaved.
|
||||
let guest_write = crate::HotOp {
|
||||
op: RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(3),
|
||||
delta: AttributeDelta {
|
||||
key: "guest".into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
},
|
||||
timestamp: crate::TimeStamp { counter: 40, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.stage_ops([RegistryDelta::ChangeNetworkAttribute {
|
||||
id: NetworkId(3),
|
||||
delta: AttributeDelta {
|
||||
key: "host".into(),
|
||||
value: Some(Value::from(serde_json::json!(1))),
|
||||
},
|
||||
}])
|
||||
.expect("host op");
|
||||
host.replay_hot_op(guest_write.clone()).expect("guest op");
|
||||
host.stage_ops([add_network(9)]).expect("host op");
|
||||
let own: Vec<crate::HotOpId> = host.hot_log().iter().filter(|hot_op| hot_op.timestamp.peer == PeerId(1)).map(crate::HotOp::id).collect();
|
||||
|
||||
let crate::Retraction { ids, touched, ops } = host.retract_interaction().expect("retract").expect("the host's interaction is hot");
|
||||
assert_eq!(ops.len(), 3, "RegisterPeer and the two writes come back for a redo, the marker does not");
|
||||
assert_eq!(ids, own, "the whole open interaction is taken back");
|
||||
assert!(touched.networks.contains(&NetworkId(3)) && touched.networks.contains(&NetworkId(9)));
|
||||
assert_eq!(host.hot_log().len(), 1, "only the guest's op stays");
|
||||
assert!(!host.registry().networks.contains_key(&NetworkId(9)));
|
||||
let network = &host.registry().networks[&NetworkId(3)];
|
||||
assert!(!network.attributes.contains_key("host"), "the host's write is gone");
|
||||
assert!(network.attributes.contains_key("guest"), "the guest's concurrent write survives");
|
||||
assert!(host.retract_interaction().expect("nothing left").is_none());
|
||||
|
||||
// A late copy of a retracted op is dropped, and nothing of it ever retires.
|
||||
let late = crate::HotOp {
|
||||
op: add_network(9),
|
||||
timestamp: crate::TimeStamp { counter: 2, peer: PeerId(1) },
|
||||
sequence: own[1].sequence,
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(late.clone()).expect("dropped, not an error");
|
||||
assert_eq!(host.hot_log().len(), 1);
|
||||
assert!(host.closed_interactions().is_empty());
|
||||
|
||||
// Another peer learns of the retraction from the marks alone.
|
||||
let mut guest = Session::with_peer(PeerId(2));
|
||||
guest.commit_op_for_test(add_network(3)).expect("base");
|
||||
guest.document.working_registry = guest.document.retired_snapshot.clone();
|
||||
guest.replay_hot_op(late).expect("the host's op reached the guest");
|
||||
assert!(guest.registry().networks.contains_key(&NetworkId(9)));
|
||||
let touched = guest.absorb_retired_marks(host.retired_marks());
|
||||
assert!(touched.networks.contains(&NetworkId(9)));
|
||||
assert!(!guest.registry().networks.contains_key(&NetworkId(9)));
|
||||
assert!(guest.hot_log().is_empty());
|
||||
}
|
||||
|
||||
/// An author's ops can reach the retirer out of order through a re-announcement after a lapsed link.
|
||||
/// Coarsening keeps the newest write by stamp, not log position, so the retired delta matches every working registry.
|
||||
#[test]
|
||||
fn an_interaction_that_arrived_out_of_order_retires_to_its_newest_write() {
|
||||
let mut author = Session::with_peer(PeerId(2));
|
||||
author.stage_ops(vec![set_attribute("name", 1), set_attribute("name", 2)]).expect("stage");
|
||||
author.end_interaction().expect("close");
|
||||
let ops = author.hot_log().to_vec();
|
||||
|
||||
let mut in_order = Session::with_peer(PeerId(1));
|
||||
let mut reversed = Session::with_peer(PeerId(1));
|
||||
for hot_op in &ops {
|
||||
in_order.replay_hot_op(hot_op.clone()).expect("replay");
|
||||
}
|
||||
for hot_op in ops.iter().rev() {
|
||||
reversed.replay_hot_op(hot_op.clone()).expect("replay");
|
||||
}
|
||||
for host in [&mut in_order, &mut reversed] {
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
host.retire_interaction(&closed[0]).expect("retire");
|
||||
assert!(host.registry().value_equal(host.retired_registry()), "the retired value is the one the working registry showed");
|
||||
}
|
||||
assert_eq!(reversed.retired_registry(), in_order.retired_registry(), "arrival order decides nothing");
|
||||
}
|
||||
|
||||
/// An interaction retires coarsened: of the writes to one field only the newest becomes a delta, a
|
||||
/// whole-list input write supersedes the slot writes before it, a write wiring an input to a node stays
|
||||
/// while what supersedes it wires elsewhere, and the fold is the one every op would have produced.
|
||||
#[test]
|
||||
fn an_interaction_retires_to_one_delta_per_field() {
|
||||
let attribute = |value: u32| set_attribute("name", value);
|
||||
let wire = |target: u64| RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: crate::NodeInput::Node { id: NodeId(target), index: 0 },
|
||||
};
|
||||
let value = |value: u32| RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 1,
|
||||
new_input: crate::NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(value)),
|
||||
exposed: false,
|
||||
},
|
||||
};
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
host.commit_op_for_test(add_network(3)).expect("network");
|
||||
host.document.working_registry = host.document.retired_snapshot.clone();
|
||||
let node = |id: u64| RegistryDelta::AddNode {
|
||||
id: NodeId(id),
|
||||
node: crate::Node::new(NetworkId(3), crate::Implementation::ProtoNode(ResourceId::from(7)), 2),
|
||||
};
|
||||
let ops = vec![node(1), node(2), node(4), attribute(1), value(1), attribute(2), wire(2), value(2), wire(4), attribute(3), value(3)];
|
||||
let mut raw = host.clone();
|
||||
raw.stage_ops(ops.clone()).expect("stage");
|
||||
host.stage_ops(ops).expect("stage");
|
||||
host.end_interaction().expect("close");
|
||||
raw.end_interaction().expect("close");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
let coarsened = host.retire_interaction(&closed[0]).expect("retire");
|
||||
let raw_ids: Vec<crate::HotOpId> = raw.hot_log().iter().map(crate::HotOp::id).collect();
|
||||
let uncoarsened = raw.retire_hot_ops(&raw_ids).expect("retire raw");
|
||||
|
||||
assert_eq!(uncoarsened.len(), 12, "RegisterPeer, three additions and eight writes");
|
||||
assert_eq!(
|
||||
coarsened.len(),
|
||||
8,
|
||||
"RegisterPeer, three additions, the newest attribute, the newest value, and both wires: {coarsened:?}"
|
||||
);
|
||||
assert!(host.hot_log().is_empty());
|
||||
assert!(host.retired_registry().value_equal(raw.retired_registry()), "the fold is unchanged");
|
||||
assert!(host.registry().value_equal(host.retired_registry()), "the working registry, built from every op, agrees");
|
||||
assert_eq!(host.retired_registry(), raw.retired_registry(), "stamps included: the survivor keeps its own");
|
||||
let kinds: Vec<&RegistryDelta> = host.history().map(|delta| &delta.kind).collect();
|
||||
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeDocumentAttribute { .. })).count() == 1);
|
||||
assert!(
|
||||
kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 0, .. })).count() == 2,
|
||||
"the wire to node 2 stays as evidence node 2 exists"
|
||||
);
|
||||
assert!(kinds.iter().filter(|kind| matches!(kind, RegistryDelta::ChangeNodeInput { index: 1, .. })).count() == 1);
|
||||
assert!(host.history().last().is_some_and(|delta| delta.is_interaction_end()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_peer_registration_wins_in_any_order() {
|
||||
// Registration rides the staging path, so the steps go through the hot log and retire.
|
||||
@@ -312,26 +78,6 @@ fn a_batch_past_the_last_sequence_is_refused_whole() {
|
||||
assert!(session.hot_log().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retraction_settles_its_sequences_so_later_interactions_stay_contiguous() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
session.stage_ops([set_attribute("a", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
let up_to = session.hot_log().last().unwrap().timestamp;
|
||||
session.retire(up_to).unwrap();
|
||||
session.stage_ops([set_attribute("b", 1)]).unwrap();
|
||||
session.retract_interaction().unwrap();
|
||||
|
||||
session.stage_ops([set_attribute("c", 1)]).unwrap();
|
||||
session.end_interaction().unwrap();
|
||||
let closed = session.closed_interactions();
|
||||
assert!(closed[0].contiguous, "the retracted sequences are not a gap");
|
||||
session.retire_interaction(&closed[0]).unwrap();
|
||||
let marks = session.retired_marks();
|
||||
assert!(marks.retired_runs.is_empty(), "retired and retracted together leave one prefix");
|
||||
assert_eq!(marks.retired_up_to[&PeerId(1)], session.last_hot_sequence());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reopened_session_drops_a_late_copy_of_a_retired_op() {
|
||||
let op = crate::HotOp {
|
||||
@@ -434,7 +180,68 @@ fn a_retired_late_copy_still_advances_the_sequence_and_the_clock() {
|
||||
assert!(next.timestamp > own.timestamp, "a later stamp");
|
||||
}
|
||||
|
||||
/// The end of an interaction can ride on its last write: a flagged write closes it as a `Meta` op does.
|
||||
#[test]
|
||||
fn only_closed_interactions_are_listed_and_the_marker_commits_nothing() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
|
||||
assert!(host.end_interaction().expect("nothing to close").is_empty(), "no op of this peer is open");
|
||||
|
||||
// The guest's open interaction is stamped before everything the host does.
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("guest op");
|
||||
|
||||
host.stage_ops([set_attribute("host", 1)]).expect("host op");
|
||||
let marker = host.end_interaction().expect("close").pop().expect("the host's interaction was open");
|
||||
assert!(matches!(marker.op, RegistryDelta::Meta) && marker.ends_interaction());
|
||||
assert!(host.end_interaction().expect("nothing more to close").is_empty(), "closing twice stages nothing");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1, "the guest's open interaction is not listed: {closed:?}");
|
||||
assert_eq!(closed[0].author, PeerId(1));
|
||||
assert!(closed[0].contiguous);
|
||||
assert_eq!(closed[0].ops.len(), 3, "RegisterPeer, the attribute write and the marker");
|
||||
|
||||
let revs = host.retire_hot_ops(&closed[0].ops).expect("retire");
|
||||
assert_eq!(revs.len(), 2, "the marker commits no delta");
|
||||
assert_eq!(host.hot_log().len(), 2, "the guest's ops stay hot");
|
||||
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker");
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].author, PeerId(2));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interaction_with_a_gap_is_not_contiguous_until_the_gap_fills() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
let guest_op = |counter: u64, sequence: u64, op: RegistryDelta| crate::HotOp {
|
||||
op,
|
||||
timestamp: crate::TimeStamp { counter, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(sequence),
|
||||
attributes: Default::default(),
|
||||
};
|
||||
host.replay_hot_op(guest_op(10, 1, add_network(9))).expect("guest op");
|
||||
host.replay_hot_op(closing(guest_op(12, 3, RegistryDelta::Meta))).expect("guest marker, op 2 still in flight");
|
||||
host.replay_hot_op(closing(guest_op(13, 4, set_attribute("guest", 2)))).expect("a later interaction");
|
||||
|
||||
let closed = host.closed_interactions();
|
||||
assert_eq!(closed.len(), 2);
|
||||
assert!(!closed[0].contiguous);
|
||||
assert!(!closed[1].contiguous, "the gap is behind the later interaction too");
|
||||
|
||||
host.replay_hot_op(guest_op(11, 2, set_attribute("guest", 1))).expect("the late op");
|
||||
let closed = host.closed_interactions();
|
||||
assert!(closed.iter().all(|interaction| interaction.contiguous));
|
||||
assert_eq!(closed[0].ops.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flagged_write_closes_its_interaction() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
@@ -452,3 +259,8 @@ fn a_flagged_write_closes_its_interaction() {
|
||||
assert_eq!(closed.len(), 1);
|
||||
assert_eq!(closed[0].ops.len(), 2, "both writes, and no marker of its own");
|
||||
}
|
||||
|
||||
fn closing(mut hot_op: crate::HotOp) -> crate::HotOp {
|
||||
hot_op.attributes.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), crate::TimeStamp::ORIGIN);
|
||||
hot_op
|
||||
}
|
||||
@@ -161,7 +161,7 @@ fn history_is_causal_and_deterministic() {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: crate::AttributeDelta {
|
||||
key: key.to_string(),
|
||||
@@ -170,6 +170,73 @@ pub(super) fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
|
||||
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
|
||||
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
|
||||
#[test]
|
||||
fn merge_converges_to_identical_history() {
|
||||
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
|
||||
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
|
||||
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
#[test]
|
||||
fn resurrection_reaches_across_a_merge() {
|
||||
let network_id = NetworkId(7);
|
||||
|
||||
// Shared base, then peer B adds and removes network 7 on its own branch.
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
})
|
||||
.expect("B AddNetwork");
|
||||
session_b
|
||||
.commit_op_for_test(RegistryDelta::RemoveNetwork {
|
||||
id: network_id,
|
||||
snapshot: Network::default(),
|
||||
})
|
||||
.expect("B RemoveNetwork");
|
||||
|
||||
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
|
||||
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
|
||||
|
||||
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
|
||||
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
|
||||
session_a
|
||||
.commit_op_for_test(RegistryDelta::SetNetworkExport {
|
||||
id: network_id,
|
||||
index: 0,
|
||||
export: None,
|
||||
})
|
||||
.expect("resurrection must find the AddNetwork on the merged-in branch");
|
||||
}
|
||||
|
||||
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
|
||||
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
|
||||
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
|
||||
@@ -884,7 +951,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone.
|
||||
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
@@ -898,7 +965,7 @@ fn add_network(id: u64) -> RegistryDelta {
|
||||
RegistryDelta::AddNetwork { id: NetworkId(id), network }
|
||||
}
|
||||
|
||||
pub(super) fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
|
||||
let delta = crate::AttributeDelta {
|
||||
key: key.into(),
|
||||
value: Some(Value::from(value)),
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use core_types::uuid::NodeId as RuntimeNodeId;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
|
||||
use crate::{NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
|
||||
|
||||
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A root network holding a proto node and a group, with another proto node and a nested group inside
|
||||
/// the group, so projection is exercised two networks deep.
|
||||
fn nested_network() -> NodeNetwork {
|
||||
let inner = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
|
||||
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let group = NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
|
||||
(
|
||||
RuntimeNodeId(21),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
|
||||
implementation: DocumentNodeImplementation::Network(inner),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
|
||||
nodes: [
|
||||
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
|
||||
(
|
||||
RuntimeNodeId(2),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
|
||||
implementation: DocumentNodeImplementation::Network(group),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn find_node<'a>(network: &'a NodeNetwork, path: &[RuntimeNodeId], id: RuntimeNodeId) -> &'a DocumentNode {
|
||||
let nested = network.nested_network(path).expect("the path should resolve");
|
||||
nested.nodes.get(&id).expect("the node should exist")
|
||||
}
|
||||
|
||||
/// A node projected alone must match the whole-document conversion, metadata included, since a mirror
|
||||
/// patched from projections has to match one rebuilt whole.
|
||||
#[test]
|
||||
fn projecting_a_node_matches_the_whole_conversion() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
for &id in registry.node_instances.keys() {
|
||||
let projected = projection.node(id).expect("every stored node projects");
|
||||
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
|
||||
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
|
||||
|
||||
assert_eq!(
|
||||
&projected.node,
|
||||
find_node(&whole, &path, local_id),
|
||||
"node {id} projected differently than the whole conversion converts it"
|
||||
);
|
||||
|
||||
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
|
||||
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
|
||||
|
||||
// The nested entries are exactly the whole conversion's entries under this node.
|
||||
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
|
||||
let expected_nested: BTreeSet<_> = node_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.storage_id)
|
||||
.collect();
|
||||
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
|
||||
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
|
||||
|
||||
let expected_networks: BTreeSet<_> = network_entries
|
||||
.iter()
|
||||
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
|
||||
.map(|entry| entry.network_id)
|
||||
.collect();
|
||||
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
|
||||
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_network_entry_projects_its_dense_exports_and_path() {
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
|
||||
let registry = &conversion.registry;
|
||||
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
|
||||
let projection = registry.runtime_projection(&conversion.declarations);
|
||||
|
||||
let root = projection.network_entry(ROOT_NETWORK).expect("root");
|
||||
assert!(root.network_path.is_empty());
|
||||
assert_eq!(root.exports, whole.exports);
|
||||
|
||||
for &network_id in registry.networks.keys() {
|
||||
let entry = projection.network_entry(network_id).expect("every stored network projects");
|
||||
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
|
||||
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
|
||||
assert_eq!(entry.scope_injections, nested.scope_injections);
|
||||
if let Some(owner) = projection.owner(network_id) {
|
||||
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
|
||||
assert_eq!(
|
||||
entry.network_path,
|
||||
[owner_path.as_slice(), &[owner_local]].concat(),
|
||||
"a network's path ends in the node implementing it"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A network no node implements is not in the runtime, so nothing inside it has an address.
|
||||
#[test]
|
||||
fn an_unreachable_network_has_no_address() {
|
||||
let mut registry = Registry::default();
|
||||
registry.networks.insert(crate::NetworkId(5), crate::Network::default());
|
||||
let mut node = Node::dummy();
|
||||
node.network = crate::NetworkId(5);
|
||||
registry.node_instances.insert(NodeId(9), node);
|
||||
|
||||
let declarations = crate::Declarations::new();
|
||||
let projection = registry.runtime_projection(&declarations);
|
||||
assert_eq!(projection.network_path(crate::NetworkId(5)), None);
|
||||
assert_eq!(projection.node_address(NodeId(9)), None);
|
||||
assert!(matches!(projection.node(NodeId(9)), Err(crate::to_runtime::ConversionError::NetworkNotFound(_))));
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -112,129 +112,6 @@ fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
|
||||
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
|
||||
}
|
||||
|
||||
/// One node in runtime form together with the metadata for it and everything nested under it, as
|
||||
/// [`RuntimeProjection::node`] produces it. Entry paths are absolute, as in a whole-document conversion.
|
||||
pub struct ProjectedNode {
|
||||
/// The runtime path of the network the node sits in.
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
pub local_id: RuntimeNodeId,
|
||||
pub node: DocumentNode,
|
||||
/// The node's own entry first, then one per nested node.
|
||||
pub node_entries: Vec<NodeMetadataEntry>,
|
||||
/// One per network the node's implementation nests, outermost first.
|
||||
pub network_entries: Vec<NetworkMetadataEntry>,
|
||||
}
|
||||
|
||||
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
|
||||
pub struct ProjectedNetwork {
|
||||
pub network_path: Vec<RuntimeNodeId>,
|
||||
/// Dense, the way the runtime holds them: a storage slot holding nothing is skipped.
|
||||
pub exports: Vec<GraphCraftNodeInput>,
|
||||
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
|
||||
pub metadata: NetworkMetadataEntry,
|
||||
}
|
||||
|
||||
/// Converts single registry entities to runtime form, for keeping a runtime mirror in step without
|
||||
/// rebuilding it. Owners are gathered once at construction so each address lookup is a probe.
|
||||
pub struct RuntimeProjection<'a> {
|
||||
context: ConversionContext<'a>,
|
||||
/// The node whose implementation each nested network is.
|
||||
owners: FxHashMap<NetworkId, NodeId>,
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
|
||||
let owners = self
|
||||
.node_instances
|
||||
.iter()
|
||||
.filter_map(|(&id, node)| match node.implementation {
|
||||
Implementation::Network(network) => Some((network, id)),
|
||||
Implementation::ProtoNode(_) => None,
|
||||
})
|
||||
.collect();
|
||||
RuntimeProjection {
|
||||
context: ConversionContext::new(self, declarations),
|
||||
owners,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimeProjection<'_> {
|
||||
/// The node implementing `network`, or `None` for the root and for a network no node implements.
|
||||
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
|
||||
self.owners.get(&network).copied()
|
||||
}
|
||||
|
||||
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
|
||||
/// `None` for a network the root does not reach, which the runtime does not hold.
|
||||
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
|
||||
let mut chain = Vec::new();
|
||||
let mut current = network;
|
||||
while current != ROOT_NETWORK {
|
||||
let owner = self.owner(current)?;
|
||||
let node = self.context.registry.node_instances.get(&owner)?;
|
||||
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
|
||||
if chain.contains(&owner) {
|
||||
return None;
|
||||
}
|
||||
chain.push(owner);
|
||||
current = node.network;
|
||||
}
|
||||
Some(chain.into_iter().rev().map(|owner| runtime_node_id(owner, &self.context.registry.node_instances[&owner])).collect())
|
||||
}
|
||||
|
||||
/// Where the node sits in the runtime: the path of its network, and its id within that network.
|
||||
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
|
||||
let node = self.context.registry.node_instances.get(&id)?;
|
||||
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
|
||||
}
|
||||
|
||||
/// The node and everything nested under it, converted the way a whole-document conversion converts
|
||||
/// them, so a mirror patched with the result matches a rebuild.
|
||||
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
|
||||
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
|
||||
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
|
||||
let local_id = runtime_node_id(id, node);
|
||||
|
||||
if let Implementation::Network(nested) = node.implementation {
|
||||
detect_network_cycle(&self.context, nested)?;
|
||||
}
|
||||
|
||||
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
|
||||
let mut network_entries = Some(Vec::new());
|
||||
Ok(ProjectedNode {
|
||||
node: convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?,
|
||||
network_path,
|
||||
local_id,
|
||||
node_entries: node_entries.expect("seeded above"),
|
||||
network_entries: network_entries.expect("seeded above"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The network's exports, scope injections and metadata, without its nodes.
|
||||
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
|
||||
let registry = self.context.registry;
|
||||
// A network removed concurrently with a write into it renders as it was, so its nodes keep their place.
|
||||
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
|
||||
|
||||
let empty_attrs = crate::Attributes::new();
|
||||
let exports = network
|
||||
.exports
|
||||
.iter()
|
||||
.filter_map(|slot| slot.target.as_ref())
|
||||
.map(|input| convert_input(registry, id, input, &empty_attrs))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(ProjectedNetwork {
|
||||
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
|
||||
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
|
||||
exports,
|
||||
network_path,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
|
||||
///
|
||||
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
|
||||
@@ -458,7 +335,7 @@ fn convert_node(
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
// Regenerated during compilation; not stored.
|
||||
context_dependencies: None,
|
||||
compile_metadata: None,
|
||||
original_location: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
//! Which entities a run of ops named, so a runtime mirror of the registry can be brought back into line
|
||||
//! without a full rebuild.
|
||||
//!
|
||||
//! Over-approximate on purpose: an op is recorded whether or not it changed anything, and the mirror
|
||||
//! settles the outcome by comparing each entity's stored and mirrored forms. That is cheaper than having
|
||||
//! every apply arm report its outcome, and stays correct when an op revives an entity it only references.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use crate::{NetworkId, NodeId, NodeInput, RegistryDelta};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Touched {
|
||||
pub nodes: BTreeSet<NodeId>,
|
||||
pub networks: BTreeSet<NetworkId>,
|
||||
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
|
||||
pub resources: bool,
|
||||
}
|
||||
|
||||
impl Touched {
|
||||
/// Records every entity `op` names: its target, and any node it references, since applying it can
|
||||
/// revive a referenced node that was concurrently removed.
|
||||
pub fn record(&mut self, op: &RegistryDelta) {
|
||||
match op {
|
||||
RegistryDelta::AddNode { id, node } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::RemoveNode { id, .. }
|
||||
| RegistryDelta::SetNodeImplementation { id, .. }
|
||||
| RegistryDelta::ChangeNodeAttribute { id, .. }
|
||||
| RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs([new_input]);
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
self.nodes.insert(*id);
|
||||
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
|
||||
}
|
||||
RegistryDelta::SetNetworkExport { id, export, .. } => {
|
||||
self.networks.insert(*id);
|
||||
self.reference_inputs(export.iter());
|
||||
}
|
||||
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
|
||||
self.networks.insert(*id);
|
||||
}
|
||||
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
|
||||
self.resources = true;
|
||||
}
|
||||
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extend(&mut self, other: Touched) {
|
||||
self.nodes.extend(other.nodes);
|
||||
self.networks.extend(other.networks);
|
||||
self.resources |= other.resources;
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
|
||||
}
|
||||
|
||||
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
|
||||
for input in inputs {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
self.nodes.insert(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{AttributeDelta, Network, Node};
|
||||
|
||||
#[test]
|
||||
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeNodeInput {
|
||||
id: NodeId(1),
|
||||
index: 0,
|
||||
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
|
||||
assert!(touched.networks.is_empty());
|
||||
assert!(!touched.resources);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_export_touches_the_network_and_the_node_it_targets() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::SetNetworkExport {
|
||||
id: NetworkId(3),
|
||||
index: 0,
|
||||
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
|
||||
});
|
||||
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::ChangeDocumentAttribute {
|
||||
delta: AttributeDelta { key: "key".into(), value: None },
|
||||
});
|
||||
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
|
||||
assert!(touched.is_empty());
|
||||
|
||||
touched.record(&RegistryDelta::SetResourceHash {
|
||||
id: crate::ResourceId::new(),
|
||||
hash: None,
|
||||
});
|
||||
assert!(touched.resources);
|
||||
assert!(touched.nodes.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_add_touches_the_node_and_what_its_inputs_reference() {
|
||||
let mut node = Node::dummy();
|
||||
node.inputs.push(crate::InputSlot {
|
||||
input: NodeInput::Node { id: NodeId(9), index: 0 },
|
||||
timestamp: crate::TimeStamp::ORIGIN,
|
||||
attributes: Default::default(),
|
||||
});
|
||||
let mut touched = Touched::default();
|
||||
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
|
||||
touched.record(&RegistryDelta::AddNetwork {
|
||||
id: NetworkId(5),
|
||||
network: Network::default(),
|
||||
});
|
||||
|
||||
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
|
||||
assert_eq!(touched.networks, BTreeSet::from([NetworkId(5)]));
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
[package]
|
||||
name = "document-live"
|
||||
description = "A memory-backed document following or hosting a collaborative session, for viewers and embedders"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
document-format = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,124 +0,0 @@
|
||||
//! A document that lives in a collaborative session rather than on disk. Hosts a session or follows
|
||||
//! one, and hands out the current runtime `NodeNetwork` on demand. Owns no executor, window, or
|
||||
//! async runtime: the caller spawns the transport driver and decides how to render.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout, ResourceProxy};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
#[error(transparent)]
|
||||
Format(#[from] FormatError),
|
||||
#[error(transparent)]
|
||||
Conversion(#[from] ConversionError),
|
||||
}
|
||||
|
||||
pub struct LiveDocument {
|
||||
gdd: GddV1,
|
||||
token: SessionToken,
|
||||
}
|
||||
|
||||
impl LiveDocument {
|
||||
/// Create an empty document and host a session under `token`. `spawn` must drive the returned
|
||||
/// future for as long as the session lives.
|
||||
pub async fn host(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let gdd = Self::empty_document(peer).await?;
|
||||
Ok(Self::host_document(gdd, signaling_server, token, user, spawn))
|
||||
}
|
||||
|
||||
/// Host a session on an already opened document.
|
||||
pub fn host_document(mut gdd: GddV1, signaling_server: &str, token: SessionToken, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Self {
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.share(room, user);
|
||||
Self { gdd, token }
|
||||
}
|
||||
|
||||
/// Join the session under `token`; the document fills in once the host's sync arrives.
|
||||
pub async fn join(signaling_server: &str, token: SessionToken, peer: PeerId, user: UserId, spawn: impl FnOnce(MessageLoopFuture)) -> Result<Self, LiveError> {
|
||||
let mut gdd = Self::empty_document(peer).await?;
|
||||
let (room, driver) = Room::connect(&token.signaling_url(signaling_server));
|
||||
spawn(driver);
|
||||
gdd.join(room, user);
|
||||
Ok(Self { gdd, token })
|
||||
}
|
||||
|
||||
async fn empty_document(peer: PeerId) -> Result<GddV1, FormatError> {
|
||||
let version = env!("CARGO_PKG_VERSION").to_string();
|
||||
GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, peer, UserId(peer.0), peer.0, version.clone(), version)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> SessionToken {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.gdd.role()
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
|
||||
/// Synced and holding every resource the document references, so `network` can be built and run.
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.is_synced() && SyncTarget::missing_resources(&self.gdd).is_empty()
|
||||
}
|
||||
|
||||
/// Resources the document references whose bytes no peer has sent yet; `is_ready` waits on them.
|
||||
pub fn missing_resources(&self) -> Vec<ResourceHash> {
|
||||
let mut missing: Vec<ResourceHash> = SyncTarget::missing_resources(&self.gdd).into_iter().collect();
|
||||
missing.sort_unstable();
|
||||
missing
|
||||
}
|
||||
|
||||
/// Apply whatever peers sent since the last call and answer their resource requests. Call it regularly.
|
||||
pub async fn poll(&mut self) -> Vec<Event> {
|
||||
let events = self.gdd.poll_peers();
|
||||
for event in &events {
|
||||
let Event::ResourceRequested { from, hash } = event else { continue };
|
||||
match self.gdd.read_resource(hash).await {
|
||||
Ok(bytes) => {
|
||||
if let Err(error) = self.gdd.send_resource(*from, *hash, bytes.as_slice().to_vec()) {
|
||||
log::warn!("Failed to send resource {hash}: {error}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("Peer asked for resource {hash} which is not in this document: {error}"),
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
pub fn document(&self) -> &GddV1 {
|
||||
&self.gdd
|
||||
}
|
||||
|
||||
pub fn document_mut(&mut self) -> &mut GddV1 {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
/// The current runtime graph, rebuilt from the registry. Async because proto-node declarations are resources.
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
/// Byte store for resources received from peers, for an executor to load from.
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
|
||||
self.gdd.resource_proxy()
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
[package]
|
||||
name = "peer-transport"
|
||||
description = "Peer-to-peer sync of hot ops and retired history between document-graph-storage sessions over WebRTC"
|
||||
rust-version.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
core-types = { workspace = true }
|
||||
document-graph-storage = { workspace = true }
|
||||
matchbox_socket = "0.14.0"
|
||||
futures = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_bytes = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
uuid = "1"
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
env_logger = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,19 +0,0 @@
|
||||
pub mod mock;
|
||||
mod packet;
|
||||
mod replica;
|
||||
mod room;
|
||||
mod target;
|
||||
mod token;
|
||||
mod transport;
|
||||
|
||||
pub use packet::{CursorPosition, CursorSpace, PacketError, Role, SyncPacket, SyncPayload};
|
||||
pub use replica::{Event, RemotePeer, Replica, ReplicaError};
|
||||
pub use room::{Incoming, Room};
|
||||
pub use target::{SyncTarget, TargetError};
|
||||
pub use token::{InvalidSessionToken, SessionToken};
|
||||
pub use transport::{Transport, TransportEvent, TransportPeerId};
|
||||
|
||||
pub use matchbox_socket::MessageLoopFuture;
|
||||
|
||||
/// Matchbox signaling server for sessions, behind TLS so browsers on HTTPS pages can reach it.
|
||||
pub const DEFAULT_SIGNALING_SERVER: &str = "wss://graphite.kobert.dev";
|
||||
@@ -1,172 +0,0 @@
|
||||
//! In-process transport for deterministic simulation. Packets wait in per-pair queues until `step` delivers
|
||||
//! one, so the seed drives interleavings while each pair stays ordered like a reliable channel.
|
||||
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use std::collections::{BTreeMap, HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Shared {
|
||||
connected: Vec<TransportPeerId>,
|
||||
inboxes: HashMap<TransportPeerId, VecDeque<TransportEvent>>,
|
||||
in_flight: BTreeMap<(TransportPeerId, TransportPeerId), VecDeque<SyncPacket>>,
|
||||
next_peer: u128,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.connected.retain(|&other| other != id);
|
||||
self.in_flight.retain(|&(from, to), _| from != id && to != id);
|
||||
for &other in &self.connected.clone() {
|
||||
self.inboxes.entry(other).or_default().push_back(TransportEvent::PeerDisconnected(id));
|
||||
self.inboxes.entry(id).or_default().push_back(TransportEvent::PeerDisconnected(other));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MockNetwork {
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
rng: SplitMix64,
|
||||
}
|
||||
|
||||
impl MockNetwork {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self {
|
||||
shared: Arc::new(Mutex::new(Shared::default())),
|
||||
rng: SplitMix64(seed),
|
||||
}
|
||||
}
|
||||
|
||||
/// A new, not yet connected peer.
|
||||
pub fn endpoint(&mut self) -> MockEndpoint {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
shared.next_peer += 1;
|
||||
let id = TransportPeerId(uuid::Uuid::from_u128(shared.next_peer));
|
||||
shared.inboxes.insert(id, VecDeque::new());
|
||||
MockEndpoint {
|
||||
id,
|
||||
shared: self.shared.clone(),
|
||||
known_peers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn connect(&mut self, id: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
if shared.connected.contains(&id) {
|
||||
return;
|
||||
}
|
||||
for &other in &shared.connected.clone() {
|
||||
shared.inboxes.entry(other).or_default().push_back(TransportEvent::PeerConnected(id));
|
||||
shared.inboxes.entry(id).or_default().push_back(TransportEvent::PeerConnected(other));
|
||||
}
|
||||
shared.connected.push(id);
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self, id: TransportPeerId) {
|
||||
self.shared.lock().unwrap().disconnect(id);
|
||||
}
|
||||
|
||||
pub fn pending(&self) -> usize {
|
||||
self.shared.lock().unwrap().in_flight.values().map(VecDeque::len).sum()
|
||||
}
|
||||
|
||||
/// Deliver one in-flight packet from a randomly chosen sender/receiver pair.
|
||||
pub fn step(&mut self) -> bool {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.iter().filter(|(_, queue)| !queue.is_empty()).map(|(&key, _)| key).collect();
|
||||
if queues.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let (from, to) = queues[self.rng.below(queues.len())];
|
||||
let packet = shared.in_flight.get_mut(&(from, to)).and_then(VecDeque::pop_front).expect("queue is non-empty");
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(from, packet));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn deliver_all(&mut self) {
|
||||
while self.step() {}
|
||||
}
|
||||
|
||||
/// Deliver everything in flight to one peer only, so a test can put a packet in one peer's hands and not another's.
|
||||
pub fn deliver_to(&mut self, to: TransportPeerId) {
|
||||
let mut shared = self.shared.lock().unwrap();
|
||||
let queues: Vec<_> = shared.in_flight.keys().copied().filter(|&(_, receiver)| receiver == to).collect();
|
||||
|
||||
for key in queues {
|
||||
let packets: VecDeque<SyncPacket> = shared.in_flight.get_mut(&key).map(std::mem::take).unwrap_or_default();
|
||||
for packet in packets {
|
||||
shared.inboxes.entry(to).or_default().push_back(TransportEvent::Packet(key.0, packet));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn random_below(&mut self, bound: usize) -> usize {
|
||||
self.rng.below(bound)
|
||||
}
|
||||
}
|
||||
|
||||
/// Like a real socket, an endpoint knows only the peers whose connect events it has polled, so it can't send to
|
||||
/// a peer before greeting it.
|
||||
pub struct MockEndpoint {
|
||||
id: TransportPeerId,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
known_peers: Vec<TransportPeerId>,
|
||||
}
|
||||
|
||||
impl MockEndpoint {
|
||||
pub fn id(&self) -> TransportPeerId {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for MockEndpoint {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
if self.known_peers.contains(&to) {
|
||||
self.shared.lock().unwrap().in_flight.entry((self.id, to)).or_default().push_back(packet.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
for to in self.known_peers.clone() {
|
||||
if Some(to) != excluded {
|
||||
self.send(to, packet)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let events: Vec<_> = self.shared.lock().unwrap().inboxes.get_mut(&self.id).map(|inbox| inbox.drain(..).collect()).unwrap_or_default();
|
||||
for event in &events {
|
||||
match event {
|
||||
TransportEvent::PeerConnected(peer) => self.known_peers.push(*peer),
|
||||
TransportEvent::PeerDisconnected(peer) => self.known_peers.retain(|known| known != peer),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.shared.lock().unwrap().disconnect(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
(self.next() % bound as u64) as usize
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, UserId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The host is the single peer that retires hot ops.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Role {
|
||||
Host,
|
||||
Guest,
|
||||
/// Not yet greeted by a host. See [`Replica::connect`](crate::Replica::connect).
|
||||
Undecided,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts had got. A peer keeps its `PeerId` across a reconnect but restarts `seq`,
|
||||
/// so `epoch` names the incarnation and counters from different epochs are never compared.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerSeq {
|
||||
pub peer: PeerId,
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
}
|
||||
|
||||
/// MessagePack-encoded on the wire.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum SyncPacket {
|
||||
/// Sent first on every connection. `epoch` and `seq` anchor the receiver's counter for this sender,
|
||||
/// since earlier broadcasts were never sent to it.
|
||||
Hello {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
role: Role,
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
},
|
||||
/// `known_revs` come from `Session::known_revs`, so the host can send only what's missing.
|
||||
SyncRequest {
|
||||
known_revs: Vec<Rev>,
|
||||
},
|
||||
Sync(Box<SyncPayload>),
|
||||
Broadcast(Broadcast),
|
||||
/// Undo (`restore: false`) or redo (`restore: true`) one of the guest's retired interactions, named by its last
|
||||
/// delta. The host answers the room with a `HeadMove` or new deltas.
|
||||
UndoRequest {
|
||||
rev: Rev,
|
||||
restore: bool,
|
||||
},
|
||||
/// Move the shared head back to its ancestor `rev`, leaving the line since as a branch. The host answers the
|
||||
/// room with a `HeadMove` without copies.
|
||||
MoveRequest {
|
||||
rev: Rev,
|
||||
},
|
||||
ResourceRequest(Vec<ResourceHash>),
|
||||
Resource {
|
||||
hash: ResourceHash,
|
||||
#[serde(with = "serde_bytes")]
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// The sender's display name, sent after the hello and on change; the newest wins. Presence is not history,
|
||||
/// so it stays outside the causal broadcast.
|
||||
Profile {
|
||||
name: String,
|
||||
},
|
||||
/// The sender's pointer, `None` when it left the viewport. Sent at most once a frame; the link identifies the sender.
|
||||
Cursor {
|
||||
position: Option<CursorPosition>,
|
||||
},
|
||||
/// A peer's record of the history's users and their names. Outside the causal order, since it merges in any order.
|
||||
Metadata(HistoryMetadata),
|
||||
}
|
||||
|
||||
/// The host's answer to a `SyncRequest`. `registry` is sent only when the host recognized none of the requester's
|
||||
/// revs; otherwise `deltas` extend its history. `seen` is the host's delivery vector at snapshot time, adopted so
|
||||
/// later broadcasts line up.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SyncPayload {
|
||||
pub registry: Option<Registry>,
|
||||
pub deltas: Vec<Delta>,
|
||||
pub head: Option<Rev>,
|
||||
pub hot_log: Vec<HotOp>,
|
||||
pub known_revs: Vec<Rev>,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
/// Which hot ops are retired or taken back, so the requester drops any it holds rather than re-entering it as
|
||||
/// live work.
|
||||
pub retired: RetiredMarks,
|
||||
/// Adopted by a peer that started empty, so opening its own copy later reconnects to the same room.
|
||||
#[serde(default)]
|
||||
pub document_id: Option<u64>,
|
||||
/// So a joiner can name every author.
|
||||
#[serde(default)]
|
||||
pub metadata: HistoryMetadata,
|
||||
}
|
||||
|
||||
/// Causal broadcast envelope. `seq` numbers the sender's broadcasts from 1 within `epoch`, and `seen` is the
|
||||
/// sender's delivery vector; a receiver holds the packet until it has delivered everything in `seen`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Broadcast {
|
||||
pub epoch: u64,
|
||||
pub seq: u64,
|
||||
pub seen: Vec<PeerSeq>,
|
||||
pub body: BroadcastBody,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub enum BroadcastBody {
|
||||
HotOps(Vec<HotOp>),
|
||||
/// `deltas` are in causal order. `retires` names the hot ops they replace, empty for a plain history transfer.
|
||||
Deltas {
|
||||
deltas: Vec<Delta>,
|
||||
retires: Vec<HotOpId>,
|
||||
},
|
||||
/// Hot ops their author took back: they leave every hot log and never retire.
|
||||
Retract(Vec<HotOpId>),
|
||||
/// Everything a peer knows is retired, re-announced with hot ops on a membership change so a peer that joined
|
||||
/// during a retirement or retraction still hears of it.
|
||||
RetiredMarks(RetiredMarks),
|
||||
/// The host dropped a retired interaction out of the line: every peer walks back and follows the head.
|
||||
HeadMove(HeadMove),
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PacketError {
|
||||
#[error("failed to encode packet: {0}")]
|
||||
Encode(#[from] rmp_serde::encode::Error),
|
||||
#[error("failed to decode packet: {0}")]
|
||||
Decode(#[from] rmp_serde::decode::Error),
|
||||
}
|
||||
|
||||
impl SyncPacket {
|
||||
pub fn encode(&self) -> Result<Box<[u8]>, PacketError> {
|
||||
Ok(rmp_serde::to_vec(self)?.into_boxed_slice())
|
||||
}
|
||||
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self, PacketError> {
|
||||
Ok(rmp_serde::from_slice(bytes)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// A peer's pointer, with its space so it is drawn only where it means something.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CursorPosition {
|
||||
pub position: [f64; 2],
|
||||
pub space: CursorSpace,
|
||||
/// Icon name of the peer's tool, shown beside the pointer; `None` from a viewer with no tools.
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum CursorSpace {
|
||||
/// Document coordinates over the canvas.
|
||||
Document,
|
||||
/// Node-graph coordinates in the network at this node-id path from the document network.
|
||||
Graph { network: Vec<u64> },
|
||||
}
|
||||
@@ -1,968 +0,0 @@
|
||||
use crate::packet::{Broadcast, BroadcastBody, CursorPosition, PacketError, PeerSeq, Role, SyncPacket, SyncPayload};
|
||||
use crate::target::{SyncTarget, TargetError};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, ResourceHash, Rev, UserId};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub enum Event {
|
||||
PeerJoined {
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
},
|
||||
PeerLeft {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// This peer's own role changed: it took over from a departed host, stepped aside unsynced, or yielded to a lower id.
|
||||
RoleChanged {
|
||||
role: Role,
|
||||
},
|
||||
/// A peer's display name arrived or changed.
|
||||
ProfileChanged {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// A peer's pointer moved, or left the viewport.
|
||||
CursorMoved {
|
||||
peer: PeerId,
|
||||
},
|
||||
/// Something on record about the history's users changed, from a peer or a sync.
|
||||
MetadataChanged,
|
||||
/// The guest has applied the host's state.
|
||||
Synced,
|
||||
/// Remote ops changed the target.
|
||||
Changed,
|
||||
ResourceReceived {
|
||||
hash: ResourceHash,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// The target couldn't serve this synchronously; answer with `send_resource`.
|
||||
ResourceRequested {
|
||||
from: TransportPeerId,
|
||||
hash: ResourceHash,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReplicaError {
|
||||
#[error(transparent)]
|
||||
Packet(#[from] PacketError),
|
||||
#[error(transparent)]
|
||||
Target(#[from] TargetError),
|
||||
}
|
||||
|
||||
/// A peer in the room as its last hello described it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct RemotePeer {
|
||||
pub peer: PeerId,
|
||||
pub user: UserId,
|
||||
pub role: Role,
|
||||
/// Empty until its profile arrives.
|
||||
pub name: String,
|
||||
/// In document space; `None` when not over the viewport.
|
||||
pub cursor: Option<CursorPosition>,
|
||||
}
|
||||
|
||||
/// How far one peer's broadcasts have been delivered here.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PeerProgress {
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
}
|
||||
|
||||
/// Broadcasts arriving before the host's `Sync` are held back, since they target state the guest doesn't have yet.
|
||||
enum SyncState {
|
||||
Synced,
|
||||
AwaitingSync { pending: Vec<(PeerId, Broadcast)> },
|
||||
}
|
||||
|
||||
/// Protocol state for one peer in a room. Owns no document; `poll` applies into a `SyncTarget`.
|
||||
///
|
||||
/// Broadcasts are delivered in causal order: each carries the sender's sequence number and delivery
|
||||
/// vector, and is held until everything the sender had delivered has been delivered here too.
|
||||
pub struct Replica {
|
||||
transport: Box<dyn Transport>,
|
||||
role: Role,
|
||||
peer: PeerId,
|
||||
user: UserId,
|
||||
/// Sent with every hello and on change.
|
||||
name: String,
|
||||
peers: HashMap<TransportPeerId, RemotePeer>,
|
||||
/// The role each link was last greeted with, so a link greeted before a role change is greeted again.
|
||||
greeted: HashMap<TransportPeerId, Role>,
|
||||
sync: SyncState,
|
||||
/// Drawn fresh so a reconnect or a reload never reuses one. See [`PeerSeq`].
|
||||
epoch: u64,
|
||||
seq: u64,
|
||||
delivered: HashMap<PeerId, PeerProgress>,
|
||||
held: Vec<(PeerId, Broadcast)>,
|
||||
/// Hot ops whose referents had not arrived, retried as later ops fill the gaps. A missing entity is
|
||||
/// indistinguishable from a concurrently removed one, so the op waits rather than applying against state it does not fit.
|
||||
deferred: Vec<HotOp>,
|
||||
/// Asked for and not yet received, so a standing request is not resent every poll.
|
||||
requested_resources: HashSet<ResourceHash>,
|
||||
/// Requests that arrived before the bytes did, answered once they turn up.
|
||||
owed_resources: HashMap<ResourceHash, HashSet<TransportPeerId>>,
|
||||
/// Whether the target's resource references may have moved since last examined.
|
||||
resources_stale: bool,
|
||||
/// The unanswered sync request's link, so it is asked again only if that peer stops hosting first.
|
||||
sync_requested_from: Option<TransportPeerId>,
|
||||
/// The host whose line this peer holds: the one it last synced from, or itself. Any other host calls for a
|
||||
/// sync from it, since what it retired may never have been broadcast here. See [`Self::follow_current_host`].
|
||||
synced_from: Option<PeerId>,
|
||||
}
|
||||
|
||||
impl Replica {
|
||||
pub fn host(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Host, peer, user, SyncState::Synced)
|
||||
}
|
||||
|
||||
/// Join through a link, expecting a host. The role stays undecided until that host greets, so a link into a room
|
||||
/// whose host is gone elects like anyone else rather than waiting for a greeting that never comes.
|
||||
pub fn guest(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::connect(transport, peer, user)
|
||||
}
|
||||
|
||||
/// Connect to the document's room in whichever role it calls for: a host's hello makes this peer a guest, and
|
||||
/// [`decide_role`](Self::decide_role) makes it the host if none greets in time.
|
||||
pub fn connect(transport: impl Transport + 'static, peer: PeerId, user: UserId) -> Self {
|
||||
Self::new(Box::new(transport), Role::Undecided, peer, user, SyncState::AwaitingSync { pending: Vec::new() })
|
||||
}
|
||||
|
||||
/// For a peer still undecided after the grace period: become the host unless an undecided peer with a lower id
|
||||
/// will. A room with guests is never seized; they elect among themselves when their host leaves. Returns the role taken.
|
||||
pub fn decide_role(&mut self) -> Option<Role> {
|
||||
if self.role != Role::Undecided {
|
||||
return None;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.role != Role::Undecided) {
|
||||
return None;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.peer < self.peer) {
|
||||
return None;
|
||||
}
|
||||
log::debug!("Join handshake: no host greeted, becoming the host");
|
||||
self.become_host();
|
||||
Some(Role::Host)
|
||||
}
|
||||
|
||||
/// An unsynced peer asks the known host for a sync, again only if that peer stops hosting or leaves first.
|
||||
fn ensure_sync_requested(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.is_synced() || self.sync_requested_from.is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
log::debug!("Join handshake: sync request sent to the host");
|
||||
self.sync_requested_from = Some(host);
|
||||
self.transport.send(host, &SyncPacket::SyncRequest { known_revs: target.known_revs() })
|
||||
}
|
||||
|
||||
/// A synced guest whose host is not the one it synced from syncs from it, since what that host retired may never
|
||||
/// have been broadcast here. The sync merges onto what is held.
|
||||
fn follow_current_host(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.role != Role::Guest || !self.is_synced() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(host) = self.peers.values().find(|remote| remote.role == Role::Host).map(|remote| remote.peer) else {
|
||||
return Ok(());
|
||||
};
|
||||
if self.synced_from == Some(host) {
|
||||
return Ok(());
|
||||
}
|
||||
log::debug!("Syncing from {host:?}, a host this peer has not synced from");
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = None;
|
||||
self.ensure_sync_requested(target)
|
||||
}
|
||||
|
||||
/// Ask the host for its line again, naming what is held so it sends only the rest. Broadcasts arriving meanwhile
|
||||
/// are buffered as on a first sync.
|
||||
fn request_resync(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.role == Role::Host || !self.is_synced() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
log::info!("A retired step arrived whose parent is missing here; syncing from the host again");
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = Some(host);
|
||||
self.transport.send(host, &SyncPacket::SyncRequest { known_revs: target.known_revs() })
|
||||
}
|
||||
|
||||
/// Take the host role and tell the room. Broadcasts buffered for a sync that now never comes are kept for
|
||||
/// delivery, or the sender's later ones would wait on them forever.
|
||||
fn become_host(&mut self) {
|
||||
self.role = Role::Host;
|
||||
self.synced_from = Some(self.peer);
|
||||
if let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) {
|
||||
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
|
||||
self.held.extend(worth_holding);
|
||||
}
|
||||
self.announce_role();
|
||||
}
|
||||
|
||||
/// Greet every peer again with the current role; a known peer takes it as a role change only.
|
||||
fn announce_role(&mut self) {
|
||||
let peers: Vec<TransportPeerId> = self.peers.keys().copied().collect();
|
||||
for transport_peer in peers {
|
||||
if let Err(error) = self.send_hello(transport_peer) {
|
||||
log::error!("Announcing the {:?} role: {error}", self.role);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In a room left without a host, the synced guest with the lowest id takes the role; every peer applies the
|
||||
/// same rule to the same membership, so they agree. An unsynced guest has nothing to serve, so it steps aside as
|
||||
/// undecided, which re-runs the rule on the rest through its greeting and has it sync from whoever takes over.
|
||||
fn settle_without_host(&mut self, events: &mut Vec<Event>) {
|
||||
if self.role != Role::Guest || self.peers.values().any(|remote| remote.role == Role::Host) {
|
||||
return;
|
||||
}
|
||||
if !self.is_synced() {
|
||||
log::info!("The host went before syncing this peer; waiting for whoever takes over");
|
||||
self.role = Role::Undecided;
|
||||
self.sync_requested_from = None;
|
||||
self.announce_role();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
return;
|
||||
}
|
||||
if self.peers.values().any(|remote| remote.role == Role::Guest && remote.peer < self.peer) {
|
||||
return;
|
||||
}
|
||||
log::info!("The host went; taking the host role over as the lowest synced peer");
|
||||
self.become_host();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
|
||||
fn new(transport: Box<dyn Transport>, role: Role, peer: PeerId, user: UserId, sync: SyncState) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
role,
|
||||
peer,
|
||||
user,
|
||||
name: String::new(),
|
||||
peers: HashMap::new(),
|
||||
greeted: HashMap::new(),
|
||||
sync,
|
||||
epoch: core_types::uuid::generate_uuid(),
|
||||
seq: 0,
|
||||
delivered: HashMap::new(),
|
||||
held: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
requested_resources: HashSet::new(),
|
||||
owed_resources: HashMap::new(),
|
||||
resources_stale: false,
|
||||
sync_requested_from: None,
|
||||
synced_from: (role == Role::Host).then_some(peer),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Role {
|
||||
self.role
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
matches!(self.sync, SyncState::Synced)
|
||||
}
|
||||
|
||||
/// The display name this peer announces, sent to the room on change and with every hello.
|
||||
pub fn set_name(&mut self, name: &str) -> Result<(), PacketError> {
|
||||
if self.name == name {
|
||||
return Ok(());
|
||||
}
|
||||
self.name = name.to_string();
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Profile { name: self.name.clone() })
|
||||
}
|
||||
|
||||
/// Tell the room this peer's history metadata after it changed here.
|
||||
pub fn send_metadata(&mut self, metadata: &HistoryMetadata) -> Result<(), PacketError> {
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Metadata(metadata.clone()))
|
||||
}
|
||||
|
||||
/// Tell the room where this peer's pointer is, `None` once it left the viewport. The caller coalesces to at
|
||||
/// most one call per frame.
|
||||
pub fn send_cursor(&mut self, position: Option<CursorPosition>) -> Result<(), PacketError> {
|
||||
if self.peers.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.transport.broadcast_except(None, &SyncPacket::Cursor { position })
|
||||
}
|
||||
|
||||
/// The other peers in the room, in no particular order.
|
||||
pub fn peers(&self) -> impl Iterator<Item = &RemotePeer> + '_ {
|
||||
self.peers.values()
|
||||
}
|
||||
|
||||
/// Broadcasts waiting on causal dependencies. Non-zero in an idle room means a stuck delivery.
|
||||
pub fn held_broadcasts(&self) -> usize {
|
||||
self.held.len()
|
||||
}
|
||||
|
||||
/// One line per held broadcast saying what it waits on, for inspecting a stuck room.
|
||||
#[doc(hidden)]
|
||||
pub fn describe_held(&self) -> Vec<String> {
|
||||
self.held
|
||||
.iter()
|
||||
.map(|(sender, broadcast)| {
|
||||
let progress = self.delivered.get(sender).map(|progress| (progress.epoch, progress.seq));
|
||||
let unmet: Vec<String> = broadcast
|
||||
.seen
|
||||
.iter()
|
||||
.filter(|mark| mark.peer != *sender && !self.has_delivered(**mark))
|
||||
.map(|mark| format!("{:?}@{}:{} (here {:?})", mark.peer, mark.epoch, mark.seq, self.delivered.get(&mark.peer).map(|p| (p.epoch, p.seq))))
|
||||
.collect();
|
||||
format!("from {sender:?} epoch {} seq {} (delivered {progress:?}) unmet {unmet:?}", broadcast.epoch, broadcast.seq)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ops held back for a referent that had not arrived. Non-zero in an idle room means one never did.
|
||||
pub fn deferred_ops(&self) -> usize {
|
||||
self.deferred.len()
|
||||
}
|
||||
|
||||
/// Resources asked for whose bytes have not come back yet.
|
||||
pub fn pending_resource_requests(&self) -> impl Iterator<Item = ResourceHash> + '_ {
|
||||
self.requested_resources.iter().copied()
|
||||
}
|
||||
|
||||
pub fn broadcast_hot_ops(&mut self, ops: &[HotOp]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// A local edit can name a resource whose bytes are not here, such as a pasted node's font.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::HotOps(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Ask the host to undo (`restore == false`) or redo (`restore == true`) this peer's retired interaction.
|
||||
/// A host undoes its own directly with [`broadcast_head_move`](Self::broadcast_head_move).
|
||||
pub fn request_undo(&mut self, rev: Rev, restore: bool) -> Result<(), PacketError> {
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.transport.send(host, &SyncPacket::UndoRequest { rev, restore })
|
||||
}
|
||||
|
||||
/// Ask the host to move the shared head to `rev`, an ancestor of it. A host moves its own directly with
|
||||
/// [`broadcast_head_move`](Self::broadcast_head_move).
|
||||
pub fn request_move(&mut self, rev: Rev) -> Result<(), PacketError> {
|
||||
let Some((&host, _)) = self.peers.iter().find(|(_, remote)| remote.role == Role::Host) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.transport.send(host, &SyncPacket::MoveRequest { rev })
|
||||
}
|
||||
|
||||
/// Host only: tell the room the head moved, with the steps minted again under it.
|
||||
pub fn broadcast_head_move(&mut self, moved: HeadMove) -> Result<(), PacketError> {
|
||||
debug_assert_eq!(self.role, Role::Host);
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::HeadMove(moved))
|
||||
}
|
||||
|
||||
/// Take back this peer's own hot ops, already gone from the local log, so every other peer drops them too.
|
||||
pub fn broadcast_retraction(&mut self, ops: &[HotOpId]) -> Result<(), PacketError> {
|
||||
if ops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = true;
|
||||
self.broadcast(BroadcastBody::Retract(ops.to_vec()))
|
||||
}
|
||||
|
||||
/// Host only.
|
||||
pub fn broadcast_retired(&mut self, deltas: &[Delta], retires: &[HotOpId]) -> Result<(), PacketError> {
|
||||
debug_assert_eq!(self.role, Role::Host);
|
||||
// An interaction of nothing but its marker retires with no delta, and the marker still has to go.
|
||||
if deltas.is_empty() && retires.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// References are read from history as well as the registry, so retiring can re-reference a hash the registry overwrote.
|
||||
self.resources_stale = true;
|
||||
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: deltas.to_vec(),
|
||||
retires: retires.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn broadcast(&mut self, body: BroadcastBody) -> Result<(), PacketError> {
|
||||
self.seq += 1;
|
||||
let broadcast = Broadcast {
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
seen: self.seen_vector(),
|
||||
body,
|
||||
};
|
||||
self.transport.broadcast(&SyncPacket::Broadcast(broadcast))
|
||||
}
|
||||
|
||||
/// Everything delivered here, including this peer's own broadcasts.
|
||||
fn seen_vector(&self) -> Vec<PeerSeq> {
|
||||
let delivered = self.delivered.iter().map(|(&peer, progress)| PeerSeq {
|
||||
peer,
|
||||
epoch: progress.epoch,
|
||||
seq: progress.seq,
|
||||
});
|
||||
delivered
|
||||
.chain([PeerSeq {
|
||||
peer: self.peer,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
}])
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.transport.close();
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, target: &mut dyn SyncTarget) -> Vec<Event> {
|
||||
let mut events = Vec::new();
|
||||
let transport_events = self.transport.poll();
|
||||
|
||||
// Greet every new peer before handling the batch. The transport adds them to its send set up front, so a
|
||||
// broadcast made meanwhile would reach them before a hello whose seq already covers it, and be skipped.
|
||||
for transport_event in &transport_events {
|
||||
if let TransportEvent::PeerConnected(transport_peer) = transport_event
|
||||
&& let Err(error) = self.send_hello(*transport_peer)
|
||||
{
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
for transport_event in transport_events {
|
||||
let result = match transport_event {
|
||||
TransportEvent::PeerConnected(_) => Ok(()),
|
||||
TransportEvent::PeerDisconnected(transport_peer) => {
|
||||
self.greeted.remove(&transport_peer);
|
||||
if self.sync_requested_from == Some(transport_peer) {
|
||||
self.sync_requested_from = None;
|
||||
}
|
||||
let departed = self.peers.remove(&transport_peer);
|
||||
log::debug!("Link {transport_peer:?} closed: {:?}", departed.as_ref().map(|remote| (remote.peer, remote.role)));
|
||||
if let Some(remote) = &departed {
|
||||
events.push(Event::PeerLeft { peer: remote.peer });
|
||||
}
|
||||
// The departed peer may have owed bytes, so let the rest be asked.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
|
||||
match departed {
|
||||
Some(remote) => {
|
||||
let closed = self.close_epoch(remote.peer, target, &mut events);
|
||||
// Any departure can settle the election, since a guest that deferred to a lower id is the
|
||||
// candidate once that id is gone. A sync asked of the departed peer goes to whoever hosts.
|
||||
self.settle_without_host(&mut events);
|
||||
closed.and_then(|()| self.ensure_sync_requested(&*target).map_err(ReplicaError::from))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
TransportEvent::Packet(transport_peer, packet) => self.handle_packet(transport_peer, packet, target, &mut events),
|
||||
TransportEvent::Malformed(transport_peer, error) => {
|
||||
log::warn!("Dropping malformed packet from {transport_peer}: {error}");
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(error) = result {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// A role decision can release broadcasts buffered for a sync that never comes, with no packet arriving.
|
||||
if !self.held.is_empty()
|
||||
&& let Err(error) = self.deliver_held(target, &mut events)
|
||||
{
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
self.retry_deferred(target, &mut events);
|
||||
|
||||
if let Err(error) = target.flush() {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.request_missing_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
if let Err(error) = self.serve_owed_resources(target) {
|
||||
log::error!("Sync error: {error}");
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
/// Re-announce every hot op held here that history does not cover, whoever wrote it, since this peer may hold
|
||||
/// the only copy of another's op. Covered ops are no-ops on every receiver.
|
||||
fn reannounce_hot_ops(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
let retired = target.retired_marks();
|
||||
let unretired: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| !retired.covers(hot_op.id())).collect();
|
||||
|
||||
self.broadcast_hot_ops(&unretired)?;
|
||||
// A retraction in flight when a peer joined never reached it and nothing re-sends it, so the marks go round too.
|
||||
if retired.retired_up_to.is_empty() && retired.retired_runs.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.broadcast(BroadcastBody::RetiredMarks(retired))
|
||||
}
|
||||
|
||||
/// Retry ops held back for a missing referent, every poll, since any later op can supply it.
|
||||
fn retry_deferred(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) {
|
||||
if self.deferred.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let pending = std::mem::take(&mut self.deferred);
|
||||
let waiting = pending.len();
|
||||
match target.apply_remote_hot_ops(pending) {
|
||||
Ok(deferred) => {
|
||||
// Nothing else in the poll notices that one applied, changing the target and maybe naming a new resource.
|
||||
if deferred.len() < waiting {
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
self.deferred = deferred;
|
||||
}
|
||||
Err(error) => log::error!("Retrying deferred hot ops: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask the room for referenced bytes not held here, after every batch since any delivered op can reference
|
||||
/// a new resource. Hashes with a standing request are skipped.
|
||||
fn request_missing_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if !self.resources_stale {
|
||||
return Ok(());
|
||||
}
|
||||
self.resources_stale = false;
|
||||
|
||||
let missing = target.missing_resources();
|
||||
// A resource that turned up some other way leaves its request behind, which would suppress a later ask.
|
||||
self.requested_resources.retain(|hash| missing.contains(hash));
|
||||
|
||||
// Sorted so `HashSet` order does not reach the wire and make a seeded run unreproducible.
|
||||
let mut unasked: Vec<ResourceHash> = missing.into_iter().filter(|hash| !self.requested_resources.contains(hash)).collect();
|
||||
unasked.sort_unstable();
|
||||
if unasked.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.requested_resources.extend(unasked.iter().copied());
|
||||
self.transport.broadcast(&SyncPacket::ResourceRequest(unasked))
|
||||
}
|
||||
|
||||
/// Answer requests that arrived before their bytes did. Runs every poll, since bytes can turn up locally and a
|
||||
/// requester never asks twice.
|
||||
fn serve_owed_resources(&mut self, target: &dyn SyncTarget) -> Result<(), PacketError> {
|
||||
if self.owed_resources.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Both loops run sorted so hash order does not decide send order and make a seeded run unreproducible.
|
||||
let mut ready: Vec<(ResourceHash, Vec<u8>)> = self.owed_resources.keys().filter_map(|&hash| target.resource_bytes(hash).map(|bytes| (hash, bytes))).collect();
|
||||
ready.sort_unstable_by_key(|(hash, _)| *hash);
|
||||
|
||||
for (hash, bytes) in ready {
|
||||
let mut recipients: Vec<TransportPeerId> = self.owed_resources.remove(&hash).unwrap_or_default().into_iter().collect();
|
||||
recipients.sort_unstable();
|
||||
|
||||
for to in recipients {
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes: bytes.clone() })?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_hello(&mut self, transport_peer: TransportPeerId) -> Result<(), ReplicaError> {
|
||||
let hello = SyncPacket::Hello {
|
||||
peer: self.peer,
|
||||
user: self.user,
|
||||
role: self.role,
|
||||
epoch: self.epoch,
|
||||
seq: self.seq,
|
||||
};
|
||||
log::debug!("Join handshake: hello sent to {transport_peer:?} as {:?}", self.role);
|
||||
self.transport.send(transport_peer, &hello)?;
|
||||
self.greeted.insert(transport_peer, self.role);
|
||||
if !self.name.is_empty() {
|
||||
self.transport.send(transport_peer, &SyncPacket::Profile { name: self.name.clone() })?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_packet(&mut self, from: TransportPeerId, packet: SyncPacket, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
match packet {
|
||||
SyncPacket::Hello { peer, user, role, epoch, seq } => {
|
||||
log::debug!("Join handshake: hello from {peer:?} ({role:?}), synced {}", self.is_synced());
|
||||
// A re-greeting over the same link and epoch announces a role; re-anchoring would strand its held broadcasts.
|
||||
let known = self.peers.contains_key(&from) && self.delivered.get(&peer).is_some_and(|progress| progress.epoch == epoch);
|
||||
// A re-greeting keeps the presence the link already announced.
|
||||
let presence = self.peers.remove(&from);
|
||||
self.peers.insert(
|
||||
from,
|
||||
RemotePeer {
|
||||
peer,
|
||||
user,
|
||||
role,
|
||||
name: presence.as_ref().map(|remote| remote.name.clone()).unwrap_or_default(),
|
||||
cursor: presence.and_then(|remote| remote.cursor),
|
||||
},
|
||||
);
|
||||
if !known {
|
||||
self.anchor_delivered(peer, epoch, seq);
|
||||
|
||||
// Can unblock broadcasts held against an earlier link's counter.
|
||||
self.deliver_held(target, events)?;
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
events.push(Event::PeerJoined { peer, user });
|
||||
// A fresh peer may hold bytes nobody else here could serve.
|
||||
self.requested_resources.clear();
|
||||
self.resources_stale = true;
|
||||
}
|
||||
|
||||
if role == Role::Host && self.role == Role::Undecided {
|
||||
self.role = Role::Guest;
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
// Two hosts meet briefly when elections ran on differing memberships; the lower id keeps the role.
|
||||
if role == Role::Host && self.role == Role::Host && peer < self.peer {
|
||||
log::info!("Yielding the host role to {peer:?}, which has the lower id");
|
||||
self.role = Role::Guest;
|
||||
// Sync from it below, handing over what this peer retired alone, and tell the room so nobody
|
||||
// keeps asking this peer for what only a host answers.
|
||||
self.sync = SyncState::AwaitingSync { pending: Vec::new() };
|
||||
self.sync_requested_from = None;
|
||||
self.announce_role();
|
||||
events.push(Event::RoleChanged { role: self.role });
|
||||
}
|
||||
self.follow_current_host(&*target)?;
|
||||
// A link greeted with an earlier role before it became a known peer hears the current one, or a
|
||||
// guest joining as the host changes would never learn who hosts.
|
||||
if self.greeted.get(&from) != Some(&self.role) {
|
||||
self.send_hello(from)?;
|
||||
}
|
||||
// The peer asked for a sync stopped hosting before answering.
|
||||
if self.sync_requested_from == Some(from) && role != Role::Host {
|
||||
self.sync_requested_from = None;
|
||||
}
|
||||
self.ensure_sync_requested(&*target)?;
|
||||
// A host yielding or a guest stepping aside can leave the room hostless or make this peer the lowest candidate.
|
||||
if role != Role::Host {
|
||||
self.settle_without_host(events);
|
||||
}
|
||||
}
|
||||
SyncPacket::UndoRequest { rev, restore } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
// Best effort: a request naming a step no longer on this host's line is reported and dropped.
|
||||
let outcome: Result<(), TargetError> = if restore {
|
||||
target.restore_interaction(rev).and_then(|deltas| self.broadcast_retired(&deltas, &[]).map_err(TargetError::from))
|
||||
} else {
|
||||
target.drop_interaction(rev).and_then(|moved| self.broadcast_head_move(moved).map_err(TargetError::from))
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => events.push(Event::Changed),
|
||||
Err(error) => log::error!("Undo request for {rev:?} failed: {error}"),
|
||||
}
|
||||
}
|
||||
SyncPacket::MoveRequest { rev } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
let outcome = target.move_head_to(rev).and_then(|moved| self.broadcast_head_move(moved).map_err(TargetError::from));
|
||||
match outcome {
|
||||
Ok(()) => events.push(Event::Changed),
|
||||
Err(error) => log::error!("Move request to {rev:?} failed: {error}"),
|
||||
}
|
||||
}
|
||||
SyncPacket::SyncRequest { known_revs } => {
|
||||
if self.role != Role::Host {
|
||||
return Ok(());
|
||||
}
|
||||
let shares_history = known_revs.iter().any(|&rev| target.contains_rev(rev));
|
||||
log::debug!("Join handshake: sync request from {from:?}, shares history {shares_history}");
|
||||
let sync = SyncPayload {
|
||||
registry: (!shares_history).then(|| target.retired_registry()),
|
||||
deltas: target.deltas_unknown_to(&known_revs),
|
||||
head: target.head(),
|
||||
hot_log: target.hot_log(),
|
||||
known_revs: target.known_revs(),
|
||||
seen: self.seen_vector(),
|
||||
retired: target.retired_marks(),
|
||||
document_id: target.document_id(),
|
||||
metadata: target.metadata(),
|
||||
};
|
||||
log::debug!("Join handshake: sync answered with {} deltas and {} hot ops", sync.deltas.len(), sync.hot_log.len());
|
||||
self.transport.send(from, &SyncPacket::Sync(Box::new(sync)))?;
|
||||
}
|
||||
SyncPacket::Sync(sync) => {
|
||||
log::debug!("Join handshake: sync received with {} deltas, full registry {}", sync.deltas.len(), sync.registry.is_some());
|
||||
self.sync_requested_from = None;
|
||||
let SyncState::AwaitingSync { pending } = std::mem::replace(&mut self.sync, SyncState::Synced) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.synced_from = self.peers.get(&from).map(|remote| remote.peer);
|
||||
// A full registry replaces a fresh copy's session, so its unretired ops, possibly the only copy of
|
||||
// what never reached the host, are replayed on top. A copy with retired history is never replaced,
|
||||
// or a host over an empty document would wipe it; its line merges and what the host lacks goes back.
|
||||
let full = sync.registry.is_some() && target.known_revs().is_empty();
|
||||
let held = if full { target.hot_log() } else { Vec::new() };
|
||||
|
||||
match (full, sync.registry) {
|
||||
(true, Some(registry)) => target.load(registry, sync.deltas, sync.head)?,
|
||||
_ => target.merge_remote(sync.deltas, &[], sync.head)?,
|
||||
}
|
||||
// A copy that joined by link takes the room's document id, or its own link would name an empty room.
|
||||
if let Some(document_id) = sync.document_id
|
||||
&& target.document_id() != Some(document_id)
|
||||
{
|
||||
target.adopt_document_id(document_id)?;
|
||||
}
|
||||
target.absorb_retired_marks(&sync.retired)?;
|
||||
if target.absorb_metadata(&sync.metadata)? {
|
||||
events.push(Event::MetadataChanged);
|
||||
}
|
||||
// Metadata recorded here while apart reaches the room too.
|
||||
let own = target.metadata();
|
||||
if !own.is_empty() {
|
||||
self.transport.broadcast_except(None, &SyncPacket::Metadata(own))?;
|
||||
}
|
||||
|
||||
self.deferred.extend(target.apply_remote_hot_ops(held)?);
|
||||
self.deferred.extend(target.apply_remote_hot_ops(sync.hot_log)?);
|
||||
self.resources_stale = true;
|
||||
|
||||
// This peer may hold the only copy of an op that never reached the host.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
|
||||
// Broadcasts the host delivered before answering are in the snapshot.
|
||||
for mark in sync.seen {
|
||||
self.observe_delivered(mark);
|
||||
}
|
||||
let worth_holding: Vec<(PeerId, Broadcast)> = pending.into_iter().filter(|(sender, broadcast)| self.worth_holding(*sender, broadcast)).collect();
|
||||
self.held.extend(worth_holding);
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
let host_is_missing = target.deltas_unknown_to(&sync.known_revs);
|
||||
if !host_is_missing.is_empty() {
|
||||
self.broadcast(BroadcastBody::Deltas {
|
||||
deltas: host_is_missing,
|
||||
retires: Vec::new(),
|
||||
})?;
|
||||
}
|
||||
// The answering host may have yielded meanwhile.
|
||||
self.follow_current_host(&*target)?;
|
||||
|
||||
// Unlike retired work, hot ops exist only in flight, so a drop loses them. Re-announce our own.
|
||||
let own_hot_ops: Vec<HotOp> = target.hot_log().into_iter().filter(|hot_op| hot_op.timestamp.peer == self.peer).collect();
|
||||
self.broadcast_hot_ops(&own_hot_ops)?;
|
||||
|
||||
events.push(Event::Synced);
|
||||
}
|
||||
SyncPacket::Broadcast(broadcast) => {
|
||||
// Senders greet before broadcasting over a per-pair ordered channel, so this means the transport reordered.
|
||||
let Some(remote) = self.peers.get(&from) else {
|
||||
log::error!("Dropping a broadcast from a peer that never said hello");
|
||||
return Ok(());
|
||||
};
|
||||
let sender = remote.peer;
|
||||
match &mut self.sync {
|
||||
SyncState::AwaitingSync { pending } => pending.push((sender, broadcast)),
|
||||
SyncState::Synced => {
|
||||
if self.worth_holding(sender, &broadcast) {
|
||||
self.held.push((sender, broadcast));
|
||||
self.deliver_held(target, events)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::Profile { name } => {
|
||||
// Presence from a link that has not said hello belongs to nobody yet.
|
||||
if let Some(remote) = self.peers.get_mut(&from)
|
||||
&& remote.name != name
|
||||
{
|
||||
remote.name = name;
|
||||
events.push(Event::ProfileChanged { peer: remote.peer });
|
||||
}
|
||||
}
|
||||
SyncPacket::Cursor { position } => {
|
||||
if let Some(remote) = self.peers.get_mut(&from)
|
||||
&& remote.cursor != position
|
||||
{
|
||||
remote.cursor = position;
|
||||
events.push(Event::CursorMoved { peer: remote.peer });
|
||||
}
|
||||
}
|
||||
SyncPacket::Metadata(remote) => {
|
||||
if target.absorb_metadata(&remote)? {
|
||||
events.push(Event::MetadataChanged);
|
||||
}
|
||||
}
|
||||
SyncPacket::ResourceRequest(hashes) => {
|
||||
for hash in hashes {
|
||||
match target.resource_bytes(hash) {
|
||||
Some(bytes) => self.transport.send(from, &SyncPacket::Resource { hash, bytes })?,
|
||||
None => {
|
||||
self.owed_resources.entry(hash).or_default().insert(from);
|
||||
events.push(Event::ResourceRequested { from, hash });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
SyncPacket::Resource { hash, bytes } => {
|
||||
if ResourceHash::from(bytes.as_slice()) != hash {
|
||||
log::warn!("Resource from {from} does not match its hash; dropping");
|
||||
return Ok(());
|
||||
}
|
||||
target.store_resource(hash, &bytes)?;
|
||||
self.requested_resources.remove(&hash);
|
||||
events.push(Event::ResourceReceived { hash, bytes });
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record that a peer's broadcasts up to `mark` need not be waited for. Monotonic, since a hello and a host's
|
||||
/// `seen` vector can carry the same fact in either order.
|
||||
fn observe_delivered(&mut self, mark: PeerSeq) {
|
||||
if mark.peer == self.peer {
|
||||
return;
|
||||
}
|
||||
match self.delivered.get_mut(&mark.peer) {
|
||||
Some(progress) if progress.epoch == mark.epoch => progress.seq = progress.seq.max(mark.seq),
|
||||
Some(_) => {}
|
||||
None => {
|
||||
self.delivered.insert(mark.peer, PeerProgress { epoch: mark.epoch, seq: mark.seq });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set where a peer's broadcasts resume on a new link. Replaces rather than raises, since nothing before its
|
||||
/// hello was sent here.
|
||||
fn anchor_delivered(&mut self, peer: PeerId, epoch: u64, seq: u64) {
|
||||
if peer == self.peer {
|
||||
return;
|
||||
}
|
||||
self.delivered.insert(peer, PeerProgress { epoch, seq });
|
||||
}
|
||||
|
||||
/// Settle up after a peer leaves: its held broadcasts can never fill their gaps, and anything waiting on it is free.
|
||||
fn close_epoch(&mut self, peer: PeerId, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
// Applying its buffered broadcasts would mint orphans no departure is left to clean up, and dropping
|
||||
// them breaks no dependency since none applied yet.
|
||||
if let SyncState::AwaitingSync { pending } = &mut self.sync {
|
||||
pending.retain(|(sender, _)| *sender != peer);
|
||||
}
|
||||
self.held.retain(|(sender, _)| *sender != peer);
|
||||
|
||||
self.deliver_held(target, events)?;
|
||||
|
||||
// The departed peer's unretired work reached only some peers, and it cannot re-announce it itself.
|
||||
self.reannounce_hot_ops(&*target)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a link to this peer is open, so more of its broadcasts may turn up.
|
||||
fn is_connected(&self, peer: PeerId) -> bool {
|
||||
self.peers.values().any(|remote| remote.peer == peer)
|
||||
}
|
||||
|
||||
/// Deliver every held broadcast whose causal dependencies are met, repeating since each can unblock others.
|
||||
fn deliver_held(&mut self, target: &mut dyn SyncTarget, events: &mut Vec<Event>) -> Result<(), ReplicaError> {
|
||||
while let Some(index) = self.held.iter().position(|(sender, broadcast)| self.is_deliverable(*sender, broadcast)) {
|
||||
let (sender, broadcast) = self.held.remove(index);
|
||||
self.delivered.insert(
|
||||
sender,
|
||||
PeerProgress {
|
||||
epoch: broadcast.epoch,
|
||||
seq: broadcast.seq,
|
||||
},
|
||||
);
|
||||
|
||||
// Best effort: a failure is reported rather than abandoning the bookkeeping and the rest of the queue.
|
||||
let applied = match broadcast.body {
|
||||
BroadcastBody::HotOps(ops) => target.apply_remote_hot_ops(ops).map(|deferred| self.deferred.extend(deferred)),
|
||||
// A retired step whose parent never arrived here cannot apply. A guest resyncs from the host; a host
|
||||
// lets it go, since the sender's whole line arrives when the sender syncs from it.
|
||||
BroadcastBody::Deltas { deltas, .. }
|
||||
if deltas
|
||||
.iter()
|
||||
.any(|delta| delta.all_parents().any(|parent| !target.contains_rev(parent) && !deltas.iter().any(|held| held.id == parent))) =>
|
||||
{
|
||||
if self.role == Role::Host {
|
||||
log::info!("A retired step arrived whose parent is missing here; its author's line comes with its sync");
|
||||
Ok(())
|
||||
} else {
|
||||
self.request_resync(&*target).map_err(TargetError::from)
|
||||
}
|
||||
}
|
||||
// The host joins a diverged line with a merge delta, and the room follows to the joined head.
|
||||
BroadcastBody::Deltas { deltas, retires } if self.role == Role::Host => target.merge_divergent(deltas, &retires).and_then(|minted| {
|
||||
if minted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
self.broadcast(BroadcastBody::Deltas { deltas: minted, retires: Vec::new() }).map_err(TargetError::from)
|
||||
}),
|
||||
BroadcastBody::Deltas { deltas, retires } => target.merge_remote(deltas, &retires, None),
|
||||
BroadcastBody::Retract(ops) => {
|
||||
// A copy still waiting on a referent is taken back with the rest.
|
||||
self.deferred.retain(|hot_op| !ops.contains(&hot_op.id()));
|
||||
target.retract_hot_ops(&ops)
|
||||
}
|
||||
BroadcastBody::RetiredMarks(marks) => {
|
||||
self.deferred.retain(|hot_op| !marks.covers(hot_op.id()));
|
||||
target.absorb_retired_marks(&marks)
|
||||
}
|
||||
BroadcastBody::HeadMove(moved) => target.apply_head_move(&moved),
|
||||
};
|
||||
if let Err(error) = applied {
|
||||
log::error!("Applying a delivered broadcast: {error}");
|
||||
}
|
||||
|
||||
self.resources_stale = true;
|
||||
events.push(Event::Changed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_deliverable(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
let Some(progress) = self.delivered.get(&sender) else { return false };
|
||||
if progress.epoch != broadcast.epoch || broadcast.seq != progress.seq + 1 {
|
||||
return false;
|
||||
}
|
||||
|
||||
broadcast.seen.iter().all(|&mark| mark.peer == sender || self.has_delivered(mark))
|
||||
}
|
||||
|
||||
/// Whether a broadcast can still come up for delivery; a stale epoch or delivered seq never will.
|
||||
fn worth_holding(&self, sender: PeerId, broadcast: &Broadcast) -> bool {
|
||||
self.delivered.get(&sender).is_none_or(|progress| progress.epoch == broadcast.epoch && broadcast.seq > progress.seq)
|
||||
}
|
||||
|
||||
/// Whether a broadcast's dependency is met. One that never can be counts as met rather than stalling its sender.
|
||||
fn has_delivered(&self, mark: PeerSeq) -> bool {
|
||||
if mark.peer == self.peer {
|
||||
return mark.epoch != self.epoch || mark.seq <= self.seq;
|
||||
}
|
||||
match self.delivered.get(&mark.peer) {
|
||||
Some(progress) if progress.epoch != mark.epoch => true,
|
||||
Some(progress) if progress.seq >= mark.seq => true,
|
||||
// A peer with no open link sends nothing more, including one whose hello never arrived.
|
||||
_ => !self.is_connected(mark.peer),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,321 +0,0 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
use crate::transport::{Transport, TransportEvent, TransportPeerId};
|
||||
use futures::StreamExt;
|
||||
use futures::channel::mpsc::UnboundedSender;
|
||||
use matchbox_socket::{MessageLoopFuture, Packet, PeerState, WebRtcSocket};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::task::{Context, Poll, Waker};
|
||||
|
||||
const CHANNEL: usize = 0;
|
||||
/// Largest SCTP message every browser accepts.
|
||||
const CHUNK_BYTES: usize = 16 * 1024;
|
||||
const FRAME_FINAL: u8 = 1;
|
||||
const FRAME_MORE: u8 = 0;
|
||||
|
||||
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
|
||||
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
|
||||
// An empty packet still gets one frame, since chunking it would yield none.
|
||||
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
|
||||
|
||||
chunks
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, chunk)| {
|
||||
let flag = if index + 1 == chunks.len() { FRAME_FINAL } else { FRAME_MORE };
|
||||
std::iter::once(flag).chain(chunk.iter().copied()).collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Per-peer reassembly of framed packets. The channel is ordered per peer, so a packet ends at the first [`FRAME_FINAL`].
|
||||
#[derive(Default)]
|
||||
struct Reassembler {
|
||||
partial: HashMap<TransportPeerId, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Reassembler {
|
||||
/// The packet's bytes once its final chunk lands.
|
||||
fn accept(&mut self, peer: TransportPeerId, frame: &[u8]) -> Option<Vec<u8>> {
|
||||
let (&flag, chunk) = frame.split_first()?;
|
||||
let buffer = self.partial.entry(peer).or_default();
|
||||
buffer.extend_from_slice(chunk);
|
||||
|
||||
(flag == FRAME_FINAL).then(|| std::mem::take(buffer))
|
||||
}
|
||||
|
||||
/// Drop a peer's half-received packet, which nothing will complete.
|
||||
fn forget(&mut self, peer: TransportPeerId) {
|
||||
self.partial.remove(&peer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Packets that arrived and wait to be polled, and whoever is waiting for them.
|
||||
#[derive(Debug, Default)]
|
||||
struct Inbox {
|
||||
packets: VecDeque<(TransportPeerId, Packet)>,
|
||||
waker: Option<Waker>,
|
||||
/// Set once the socket loop ended: nothing more will arrive.
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
fn lock(inbox: &Mutex<Inbox>) -> std::sync::MutexGuard<'_, Inbox> {
|
||||
inbox.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
/// A handle onto a room's inbox that resolves when a packet is waiting, so the room is polled as packets arrive
|
||||
/// rather than once per frame, which a hidden browser tab gets only about once a second.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Incoming {
|
||||
inbox: Arc<Mutex<Inbox>>,
|
||||
}
|
||||
|
||||
impl Incoming {
|
||||
/// Resolves to `true` once a packet is waiting, `false` once the room's loop has ended and nothing more can arrive.
|
||||
pub async fn wait(&self) -> bool {
|
||||
std::future::poll_fn(|cx| self.poll_ready(cx)).await
|
||||
}
|
||||
|
||||
fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<bool> {
|
||||
let mut inbox = lock(&self.inbox);
|
||||
if !inbox.packets.is_empty() {
|
||||
return Poll::Ready(true);
|
||||
}
|
||||
if inbox.closed {
|
||||
return Poll::Ready(false);
|
||||
}
|
||||
inbox.waker = Some(cx.waker().clone());
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
/// One matchbox room over WebRTC, with packets split into `[flag][bytes]` chunks and reassembled per peer.
|
||||
/// The returned future must be polled continuously by the caller.
|
||||
pub struct Room {
|
||||
socket: WebRtcSocket,
|
||||
outgoing: UnboundedSender<(TransportPeerId, Packet)>,
|
||||
inbox: Arc<Mutex<Inbox>>,
|
||||
incoming: Reassembler,
|
||||
}
|
||||
|
||||
impl Room {
|
||||
pub fn connect(signaling_url: &str) -> (Self, MessageLoopFuture) {
|
||||
// WebRTC's DTLS goes through rustls, which needs one provider chosen when several are linked.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
|
||||
let (mut socket, driver) = WebRtcSocket::new_reliable(signaling_url);
|
||||
let (outgoing, mut received) = socket.take_channel(CHANNEL).expect("a reliable socket has its one channel").split();
|
||||
let inbox = Arc::new(Mutex::new(Inbox::default()));
|
||||
|
||||
// Arrivals move into the inbox and wake its waiter. The forwarder ends when the socket loop returns and
|
||||
// drops its senders; the loop's result stays the driver's.
|
||||
let forwarder = {
|
||||
let inbox = Arc::clone(&inbox);
|
||||
async move {
|
||||
while let Some(arrived) = received.next().await {
|
||||
let mut inbox = lock(&inbox);
|
||||
inbox.packets.push_back(arrived);
|
||||
if let Some(waker) = inbox.waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
let mut inbox = lock(&inbox);
|
||||
inbox.closed = true;
|
||||
if let Some(waker) = inbox.waker.take() {
|
||||
waker.wake();
|
||||
}
|
||||
}
|
||||
};
|
||||
let driver: MessageLoopFuture = Box::pin(async move {
|
||||
let (result, ()) = futures::join!(driver, forwarder);
|
||||
result
|
||||
});
|
||||
|
||||
(
|
||||
Self {
|
||||
socket,
|
||||
outgoing,
|
||||
inbox,
|
||||
incoming: Reassembler::default(),
|
||||
},
|
||||
driver,
|
||||
)
|
||||
}
|
||||
|
||||
/// A handle that resolves whenever a packet waits in this room.
|
||||
pub fn incoming(&self) -> Incoming {
|
||||
Incoming { inbox: Arc::clone(&self.inbox) }
|
||||
}
|
||||
|
||||
fn send_chunks(&mut self, bytes: &[u8], peers: &[TransportPeerId]) {
|
||||
for frame in frames(bytes) {
|
||||
for &peer in peers {
|
||||
// Fails only once the socket loop has ended, which the loop's future reports.
|
||||
if self.outgoing.unbounded_send((peer, frame.clone())).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Room {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
self.send_chunks(&bytes, &[to]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
let bytes = packet.encode()?;
|
||||
let peers: Vec<_> = self.socket.connected_peers().filter(|&peer| Some(peer) != excluded).collect();
|
||||
self.send_chunks(&bytes, &peers);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Vec<TransportEvent> {
|
||||
let mut events = Vec::new();
|
||||
|
||||
for (peer, state) in self.socket.update_peers() {
|
||||
events.push(match state {
|
||||
PeerState::Connected => TransportEvent::PeerConnected(peer),
|
||||
PeerState::Disconnected => {
|
||||
self.incoming.forget(peer);
|
||||
TransportEvent::PeerDisconnected(peer)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let received: Vec<_> = lock(&self.inbox).packets.drain(..).collect();
|
||||
for (peer, frame) in received {
|
||||
let Some(bytes) = self.incoming.accept(peer, &frame) else { continue };
|
||||
|
||||
events.push(match SyncPacket::decode(&bytes) {
|
||||
Ok(packet) => TransportEvent::Packet(peer, packet),
|
||||
Err(error) => TransportEvent::Malformed(peer, error),
|
||||
});
|
||||
}
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::FutureExt;
|
||||
|
||||
fn peer(byte: u128) -> TransportPeerId {
|
||||
TransportPeerId(uuid::Uuid::from_u128(byte))
|
||||
}
|
||||
|
||||
/// The inbox handle resolves on an arrival and once more when the loop ends, and is pending otherwise.
|
||||
#[test]
|
||||
fn the_inbox_wakes_on_arrival_and_reports_the_end() {
|
||||
let inbox = Arc::new(Mutex::new(Inbox::default()));
|
||||
let incoming = Incoming { inbox: Arc::clone(&inbox) };
|
||||
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
|
||||
|
||||
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
|
||||
|
||||
lock(&inbox).packets.clear();
|
||||
assert_eq!(incoming.wait().now_or_never(), None, "drained: pending again");
|
||||
|
||||
lock(&inbox).closed = true;
|
||||
assert_eq!(incoming.wait().now_or_never(), Some(false), "the end of the loop resolves the wait for good");
|
||||
}
|
||||
|
||||
/// Push every frame at a reassembler and collect the packets that come out.
|
||||
fn round_trip(bytes: &[u8]) -> Vec<Vec<u8>> {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
frames(bytes).into_iter().filter_map(|frame| incoming.accept(peer(1), &frame)).collect()
|
||||
}
|
||||
|
||||
/// A packet within one chunk travels as a single final frame.
|
||||
#[test]
|
||||
fn a_small_packet_is_one_frame() {
|
||||
let bytes = b"hello".to_vec();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), 1);
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&bytes), vec![bytes]);
|
||||
}
|
||||
|
||||
/// Chunking an empty packet yields no chunks, so it needs a frame of its own or it leaves no trace on the wire.
|
||||
#[test]
|
||||
fn an_empty_packet_still_produces_one_frame() {
|
||||
let framed = frames(&[]);
|
||||
|
||||
assert_eq!(framed.len(), 1, "an empty packet must still be framed");
|
||||
assert_eq!(framed[0][0], FRAME_FINAL);
|
||||
assert_eq!(round_trip(&[]), vec![Vec::<u8>::new()]);
|
||||
}
|
||||
|
||||
/// Either side of the SCTP limit: exactly one chunk stays one frame, one byte more splits, and both rebuild exactly.
|
||||
#[test]
|
||||
fn packets_around_the_chunk_boundary_round_trip() {
|
||||
for length in [CHUNK_BYTES - 1, CHUNK_BYTES, CHUNK_BYTES + 1, CHUNK_BYTES * 3 + 7] {
|
||||
let bytes: Vec<u8> = (0..length).map(|index| (index % 251) as u8).collect();
|
||||
let framed = frames(&bytes);
|
||||
|
||||
assert_eq!(framed.len(), length.div_ceil(CHUNK_BYTES), "wrong frame count for {length} bytes");
|
||||
assert!(framed.iter().all(|frame| frame.len() <= CHUNK_BYTES + 1), "a frame exceeded the SCTP limit");
|
||||
assert!(framed.iter().rev().skip(1).all(|frame| frame[0] == FRAME_MORE), "only the last frame is final");
|
||||
assert_eq!(framed.last().expect("at least one frame")[0], FRAME_FINAL);
|
||||
|
||||
assert_eq!(round_trip(&bytes), vec![bytes], "{length} bytes did not round trip");
|
||||
}
|
||||
}
|
||||
|
||||
/// Two peers' chunks interleave on one channel, so reassembly is per peer or one packet is spliced into the other.
|
||||
#[test]
|
||||
fn interleaved_peers_reassemble_separately() {
|
||||
let (first, second) = (peer(1), peer(2));
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 32).map(|index| (index % 97) as u8).collect();
|
||||
let short = b"short".to_vec();
|
||||
|
||||
let long_frames = frames(&long);
|
||||
let short_frames = frames(&short);
|
||||
assert_eq!(long_frames.len(), 2, "the long packet must span two frames to interleave");
|
||||
|
||||
// The short packet arrives whole between the long packet's two chunks.
|
||||
assert_eq!(incoming.accept(first, &long_frames[0]), None);
|
||||
assert_eq!(incoming.accept(second, &short_frames[0]), Some(short));
|
||||
assert_eq!(incoming.accept(first, &long_frames[1]), Some(long));
|
||||
}
|
||||
|
||||
/// A peer dropping mid-packet leaves a partial buffer that must not prefix the next packet under that id.
|
||||
#[test]
|
||||
fn forgetting_a_peer_discards_its_partial_packet() {
|
||||
let sender = peer(1);
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
let long: Vec<u8> = (0..CHUNK_BYTES + 8).map(|index| (index % 89) as u8).collect();
|
||||
assert_eq!(incoming.accept(sender, &frames(&long)[0]), None);
|
||||
|
||||
incoming.forget(sender);
|
||||
|
||||
let fresh = b"fresh".to_vec();
|
||||
assert_eq!(incoming.accept(sender, &frames(&fresh)[0]), Some(fresh), "the abandoned prefix must be gone");
|
||||
}
|
||||
|
||||
/// A zero-length frame carries no flag byte, so it is ignored rather than read past its end.
|
||||
#[test]
|
||||
fn an_empty_frame_is_ignored() {
|
||||
let mut incoming = Reassembler::default();
|
||||
|
||||
assert_eq!(incoming.accept(peer(1), &[]), None);
|
||||
}
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
use document_graph_storage::{Delta, HeadMove, HistoryMetadata, HotOp, HotOpId, PeerId, Registry, ResourceHash, RetiredMarks, Rev, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub type TargetError = Box<dyn std::error::Error>;
|
||||
|
||||
/// The document state a `Replica` reads from and applies remote changes to.
|
||||
pub trait SyncTarget {
|
||||
fn peer(&self) -> PeerId;
|
||||
/// The session token is derived from it. See [`SessionToken::for_document`](crate::SessionToken::for_document).
|
||||
fn document_id(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
/// Take on the host's document id after a sync, so this copy is the same document.
|
||||
fn adopt_document_id(&mut self, _document_id: u64) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
fn head(&self) -> Option<Rev>;
|
||||
fn retired_registry(&self) -> Registry;
|
||||
fn hot_log(&self) -> Vec<HotOp>;
|
||||
fn known_revs(&self) -> Vec<Rev>;
|
||||
fn contains_rev(&self, rev: Rev) -> bool;
|
||||
/// What a peer holding `known` lacks. Handing it out publishes it. See [`Session::deltas_unknown_to`].
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta>;
|
||||
|
||||
/// Which hot ops are retired or taken back. See [`Session::retired_marks`].
|
||||
fn retired_marks(&self) -> RetiredMarks;
|
||||
/// Take on a peer's marks, dropping what they cover from the hot log.
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError>;
|
||||
|
||||
/// The history's users and their names, merged last-writer-wins. Empty for a target that keeps none.
|
||||
fn metadata(&self) -> HistoryMetadata {
|
||||
HistoryMetadata::default()
|
||||
}
|
||||
/// Take on a peer's metadata. Returns whether any of it was news.
|
||||
fn absorb_metadata(&mut self, _remote: &HistoryMetadata) -> Result<bool, TargetError> {
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Replace all state with the given retired state.
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError>;
|
||||
/// Must be idempotent on structural ops, since the sync may already reflect a buffered op. Returns the ops
|
||||
/// whose referents have not arrived, for the caller to retry.
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError>;
|
||||
/// Take the host's deltas on and follow to `head`, or to the batch's last delta when `None`. See [`Session::follow`].
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError>;
|
||||
/// Host only: take a peer's deltas on, joining a diverged line with a merge delta rather than following it.
|
||||
/// Returns the absorbed deltas and the merge, for the host to broadcast so every guest follows.
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError>;
|
||||
/// A peer took back hot ops of its own: drop them and re-derive what they touched.
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError>;
|
||||
/// Host only: drop a retired interaction out of the shared line. See [`Session::drop_interaction`].
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError>;
|
||||
/// Host only: mint a dropped interaction again on top of the line. See [`Session::restore_interaction`].
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError>;
|
||||
/// Host only: move the shared head to an ancestor, leaving the line since as a branch. See [`Session::move_head_to`].
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let _ = rev;
|
||||
Err("this target cannot move its head".into())
|
||||
}
|
||||
/// Follow the host's cursor move. See [`Session::apply_head_move`].
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError>;
|
||||
/// Make everything applied since the last flush durable. Called once per [`Replica::poll`](crate::Replica::poll)
|
||||
/// so a target that rewrites whole files does it once per batch.
|
||||
fn flush(&mut self) -> Result<(), TargetError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Referenced resources whose bytes are not available locally.
|
||||
fn missing_resources(&self) -> HashSet<ResourceHash> {
|
||||
HashSet::new()
|
||||
}
|
||||
/// `None` when the bytes can't be produced synchronously; the request is then surfaced as an event.
|
||||
fn resource_bytes(&self, hash: ResourceHash) -> Option<Vec<u8>> {
|
||||
let _ = hash;
|
||||
None
|
||||
}
|
||||
fn store_resource(&mut self, hash: ResourceHash, bytes: &[u8]) -> Result<(), TargetError> {
|
||||
let _ = (hash, bytes);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl SyncTarget for Session {
|
||||
fn peer(&self) -> PeerId {
|
||||
Session::peer(self)
|
||||
}
|
||||
|
||||
fn head(&self) -> Option<Rev> {
|
||||
self.head_rev()
|
||||
}
|
||||
|
||||
fn retired_registry(&self) -> Registry {
|
||||
Session::retired_registry(self).clone()
|
||||
}
|
||||
|
||||
fn hot_log(&self) -> Vec<HotOp> {
|
||||
Session::hot_log(self).to_vec()
|
||||
}
|
||||
|
||||
fn known_revs(&self) -> Vec<Rev> {
|
||||
Session::known_revs(self)
|
||||
}
|
||||
|
||||
fn contains_rev(&self, rev: Rev) -> bool {
|
||||
self.delta(rev).is_some()
|
||||
}
|
||||
|
||||
fn deltas_unknown_to(&mut self, known: &[Rev]) -> Vec<Delta> {
|
||||
Session::deltas_unknown_to(self, known.iter().copied())
|
||||
}
|
||||
|
||||
fn load(&mut self, registry: Registry, history: Vec<Delta>, head: Option<Rev>) -> Result<(), TargetError> {
|
||||
// A spent sequence must not come round again, or a new op of this peer's would be taken as retired.
|
||||
let spent = self.last_hot_sequence();
|
||||
*self = Session::load(self.peer(), self.user(), registry, history, head, Vec::new(), self.next_node_counter());
|
||||
self.restore_hot_sequence(spent);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_remote_hot_ops(&mut self, ops: Vec<HotOp>) -> Result<Vec<HotOp>, TargetError> {
|
||||
// Every op gets its turn even if one fails, since its broadcast is already consumed. A failure usually
|
||||
// means a referent has not arrived, so the op is handed back to retry.
|
||||
let mut deferred = Vec::new();
|
||||
for hot_op in ops {
|
||||
if self.replay_hot_op(hot_op.clone()).is_err() {
|
||||
deferred.push(hot_op);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(deferred)
|
||||
}
|
||||
|
||||
fn merge_remote(&mut self, deltas: Vec<Delta>, retires: &[HotOpId], head: Option<Rev>) -> Result<(), TargetError> {
|
||||
self.follow(deltas, head)?;
|
||||
self.discard_hot_ops(retires);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn merge_divergent(&mut self, deltas: Vec<Delta>, retires: &[HotOpId]) -> Result<Vec<Delta>, TargetError> {
|
||||
let mut absorbed: Vec<Delta> = deltas.iter().filter(|delta| !self.contains_rev(delta.id)).cloned().collect();
|
||||
let outcome = self.merge(deltas)?;
|
||||
self.discard_hot_ops(retires);
|
||||
if let document_graph_storage::MergeOutcome::Merged(rev) = outcome {
|
||||
absorbed.extend(self.delta(rev).cloned());
|
||||
}
|
||||
Ok(absorbed)
|
||||
}
|
||||
|
||||
fn retired_marks(&self) -> RetiredMarks {
|
||||
Session::retired_marks(self).clone()
|
||||
}
|
||||
|
||||
fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Result<(), TargetError> {
|
||||
Session::absorb_retired_marks(self, remote);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn retract_hot_ops(&mut self, ops: &[HotOpId]) -> Result<(), TargetError> {
|
||||
Session::retract_hot_ops(self, ops);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drop_interaction(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
let (moved, _) = Session::drop_interaction(self, rev)?;
|
||||
Ok(moved)
|
||||
}
|
||||
|
||||
fn restore_interaction(&mut self, rev: Rev) -> Result<Vec<Delta>, TargetError> {
|
||||
let revs = Session::restore_interaction(self, rev)?;
|
||||
Ok(revs.into_iter().filter_map(|rev| self.delta(rev).cloned()).collect())
|
||||
}
|
||||
|
||||
fn apply_head_move(&mut self, moved: &HeadMove) -> Result<(), TargetError> {
|
||||
Session::apply_head_move(self, moved)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn move_head_to(&mut self, rev: Rev) -> Result<HeadMove, TargetError> {
|
||||
Ok(Session::move_head_to(self, rev)?.0)
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Identifies the text form as a Graphite session token, like GitLab's `glpat-` tokens.
|
||||
const PREFIX: &str = "graphite-";
|
||||
|
||||
/// Random session ID, used as the matchbox room name. Entropy is supplied by the caller.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SessionToken(pub [u8; 16]);
|
||||
|
||||
impl SessionToken {
|
||||
pub fn signaling_url(&self, signaling_server: &str) -> String {
|
||||
format!("{}/{}", signaling_server.trim_end_matches('/'), self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for SessionToken {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{PREFIX}{}", URL_SAFE_NO_PAD.encode(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid session token")]
|
||||
pub struct InvalidSessionToken;
|
||||
|
||||
impl FromStr for SessionToken {
|
||||
type Err = InvalidSessionToken;
|
||||
|
||||
/// Parses the bare token or a share link carrying it as the `session` query parameter, so a pasted link works
|
||||
/// wherever a token does.
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let s = s.trim();
|
||||
let s = match s.split_once("session=") {
|
||||
Some((_, rest)) => rest.split(['&', '#', ' ']).next().unwrap_or(""),
|
||||
None => s,
|
||||
};
|
||||
let encoded = s.strip_prefix(PREFIX).ok_or(InvalidSessionToken)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(encoded).map_err(|_| InvalidSessionToken)?;
|
||||
let bytes = bytes.try_into().map_err(|_| InvalidSessionToken)?;
|
||||
Ok(Self(bytes))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_string() {
|
||||
let token = SessionToken([7; 16]);
|
||||
assert_eq!(token.to_string().parse::<SessionToken>().unwrap(), token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_the_token_out_of_a_share_link() {
|
||||
let token = SessionToken([7; 16]);
|
||||
let link = format!(" https://editor.graphite.rs/?session={token}#top ");
|
||||
assert_eq!(link.parse::<SessionToken>().unwrap(), token);
|
||||
assert_eq!(format!("http://localhost:8080/?debug=1&session={token}").parse::<SessionToken>().unwrap(), token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wrong_length_or_missing_prefix() {
|
||||
assert!("graphite-AAAA".parse::<SessionToken>().is_err());
|
||||
assert!("BwcHBwcHBwcHBwcHBwcHBw".parse::<SessionToken>().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionToken {
|
||||
/// The token every copy of a document shares, so a copy edited apart reconnects by opening the file. Document
|
||||
/// ids are random, so the room is as unguessable as the id; the mixing only spreads it over the token's width.
|
||||
pub fn for_document(document_id: u64) -> Self {
|
||||
fn mix(mut value: u64) -> u64 {
|
||||
value = value.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
value = (value ^ (value >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
value = (value ^ (value >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
value ^ (value >> 31)
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..8].copy_from_slice(&mix(document_id).to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&mix(document_id ^ 0x5A5A_5A5A_5A5A_5A5A).to_le_bytes());
|
||||
Self(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod derived_token_tests {
|
||||
use super::SessionToken;
|
||||
|
||||
#[test]
|
||||
fn a_document_id_derives_one_token() {
|
||||
assert_eq!(SessionToken::for_document(7), SessionToken::for_document(7));
|
||||
assert_ne!(SessionToken::for_document(7), SessionToken::for_document(8));
|
||||
let text = SessionToken::for_document(7).to_string();
|
||||
assert_eq!(text.parse::<SessionToken>().expect("round trip"), SessionToken::for_document(7));
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
use crate::packet::{PacketError, SyncPacket};
|
||||
|
||||
pub use matchbox_socket::PeerId as TransportPeerId;
|
||||
|
||||
pub enum TransportEvent {
|
||||
PeerConnected(TransportPeerId),
|
||||
PeerDisconnected(TransportPeerId),
|
||||
Packet(TransportPeerId, SyncPacket),
|
||||
Malformed(TransportPeerId, PacketError),
|
||||
}
|
||||
|
||||
/// Packet delivery between the peers of one session. Delivery must be reliable and ordered per
|
||||
/// sender, which is what lets the `Replica` skip acknowledgement and retransmission.
|
||||
pub trait Transport: Send + Sync {
|
||||
fn send(&mut self, to: TransportPeerId, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn broadcast_except(&mut self, excluded: Option<TransportPeerId>, packet: &SyncPacket) -> Result<(), PacketError>;
|
||||
fn poll(&mut self) -> Vec<TransportEvent>;
|
||||
fn close(&mut self);
|
||||
|
||||
fn broadcast(&mut self, packet: &SyncPacket) -> Result<(), PacketError> {
|
||||
self.broadcast_except(None, packet)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+3
-3
@@ -15,7 +15,7 @@ workspace = true
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
|
||||
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
|
||||
gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
|
||||
[dependencies]
|
||||
@@ -25,7 +25,6 @@ graph-craft = { workspace = true }
|
||||
document-format = { workspace = true }
|
||||
document-graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-container = { workspace = true }
|
||||
peer-transport = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
@@ -52,7 +51,7 @@ usvg = { workspace = true }
|
||||
simplecss = { workspace = true }
|
||||
once_cell = { workspace = true }
|
||||
web-sys = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
image = { workspace = true }
|
||||
color = { workspace = true }
|
||||
@@ -65,6 +64,7 @@ wgpu-executor = { workspace = true, optional = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
wasm-bindgen-futures = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_family = "wasm"))'.dependencies]
|
||||
tokio = { workspace = true }
|
||||
|
||||
+10
-47
@@ -2,15 +2,14 @@ use crate::application::{Editor, Environment};
|
||||
use crate::dispatcher::Dispatcher;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
|
||||
use crate::task::{Scheduling, Spawn, Spawner};
|
||||
use crate::task::{Spawn, Spawner};
|
||||
use document_container::store::DocumentStore;
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphene_std::runtime::Clock;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type ReadyEditorBuilder = EditorBuilder<Wake, Environment, Arc<dyn ResourceStorage>, Arc<dyn DocumentStore>>;
|
||||
pub type ReadyRuntimeBuilder = RuntimeBuilder<Wake, PlatformApplicationIo, Arc<dyn Clock>>;
|
||||
pub type ReadyRuntimeBuilder = RuntimeBuilder<Wake, PlatformApplicationIo>;
|
||||
|
||||
pub struct Builder<E = (), R = (), S = (), N = ()> {
|
||||
editor: E,
|
||||
@@ -97,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
let RuntimeBuilder {
|
||||
wake: runtime_wake,
|
||||
mut application_io,
|
||||
scheduling,
|
||||
clock,
|
||||
} = runtime;
|
||||
|
||||
graphene_std::uuid::set_uuid_seed(random_seed);
|
||||
@@ -110,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
|
||||
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
node_runtime.replace_application_io(application_io);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
|
||||
node_runtime.set_scheduling(scheduling);
|
||||
node_runtime.replace_task_executor(spawner, runtime_wake);
|
||||
|
||||
(Editor { dispatcher }, node_runtime)
|
||||
}
|
||||
@@ -185,21 +181,14 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RuntimeBuilder<W = (), A = (), C = ()> {
|
||||
pub struct RuntimeBuilder<W = (), A = ()> {
|
||||
wake: W,
|
||||
application_io: A,
|
||||
clock: C,
|
||||
scheduling: Scheduling,
|
||||
}
|
||||
|
||||
impl RuntimeBuilder {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
wake: (),
|
||||
application_io: (),
|
||||
clock: (),
|
||||
scheduling: Scheduling::default(),
|
||||
}
|
||||
Self { wake: (), application_io: () }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,44 +198,18 @@ impl Default for RuntimeBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, C> RuntimeBuilder<(), A, C> {
|
||||
impl<A> RuntimeBuilder<(), A> {
|
||||
/// Called from any thread when a graph task has completed, to run the runtime again as soon as possible.
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder<Wake, A, C> {
|
||||
pub fn with_wake(self, wake: impl Fn() + Send + Sync + 'static) -> RuntimeBuilder<Wake, A> {
|
||||
RuntimeBuilder {
|
||||
wake: Arc::new(wake),
|
||||
application_io: self.application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, C> RuntimeBuilder<W, (), C> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo, C> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io,
|
||||
clock: self.clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A> RuntimeBuilder<W, A, ()> {
|
||||
/// The host's clock, which frames and the nodes' own budgets are measured with.
|
||||
pub fn with_clock(self, clock: Arc<dyn Clock>) -> RuntimeBuilder<W, A, Arc<dyn Clock>> {
|
||||
RuntimeBuilder {
|
||||
wake: self.wake,
|
||||
application_io: self.application_io,
|
||||
clock,
|
||||
scheduling: self.scheduling,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<W, A, C> RuntimeBuilder<W, A, C> {
|
||||
/// How the runtime schedules the evaluations finished tasks ask for, by default within a 16 ms frame budget.
|
||||
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
|
||||
Self { scheduling, ..self }
|
||||
impl<W> RuntimeBuilder<W, ()> {
|
||||
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
|
||||
RuntimeBuilder { wake: self.wake, application_io }
|
||||
}
|
||||
}
|
||||
+43
-1
@@ -11,6 +11,8 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
|
||||
pub const LAYER_INDENT_OFFSET: i32 = 8;
|
||||
/// Horizontal grid width of a non-layer node in a chain.
|
||||
pub const NODE_CHAIN_WIDTH: i32 = 7;
|
||||
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
|
||||
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
|
||||
// VIEWPORT
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
@@ -33,7 +35,7 @@ pub const VIEWPORT_SCROLL_RATE: f64 = 0.6;
|
||||
|
||||
pub const VIEWPORT_ROTATE_SNAP_INTERVAL: f64 = 15.;
|
||||
|
||||
pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.999;
|
||||
pub const VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR: f64 = 0.95;
|
||||
|
||||
pub const DRAG_BEYOND_VIEWPORT_MAX_OVEREXTENSION_PIXELS: f64 = 50.;
|
||||
pub const DRAG_BEYOND_VIEWPORT_SPEED_FACTOR: f64 = 20.;
|
||||
@@ -112,6 +114,38 @@ pub const SEGMENT_OVERLAY_SIZE: f64 = 10.;
|
||||
pub const SEGMENT_SELECTED_THICKNESS: f64 = 3.;
|
||||
pub const HANDLE_LENGTH_FACTOR: f64 = 0.5;
|
||||
|
||||
// PATH DIRECTION OVERLAYS
|
||||
// Paths shorter than this on screen get no markers
|
||||
pub const PATH_MARKERS_MIN_LENGTH: f64 = 24.;
|
||||
// From an end anchor's center to the middle of the marker beside it
|
||||
pub const PATH_END_MARKER_DISTANCE: f64 = 7.;
|
||||
pub const PATH_END_MARKER_SIZE: f64 = 9.;
|
||||
// Between arrows, stretched or squeezed slightly so a whole number of them fit evenly along each path
|
||||
pub const PATH_DIRECTION_ARROW_SPACING: f64 = 15.625;
|
||||
pub const PATH_DIRECTION_CHEVRON_SIZE: f64 = 8.;
|
||||
// How far to the right of the path its harpoons' shafts sit, apart from the path itself
|
||||
pub const PATH_DIRECTION_HARPOON_OFFSET: f64 = 3.;
|
||||
// In viewport pixels, far finer than the arrows need to sit evenly
|
||||
pub const PATH_DIRECTION_ARC_LENGTH_ACCURACY: f64 = 0.1;
|
||||
pub const PATH_INDEX_LABEL_OFFSET: f64 = 14.;
|
||||
pub const POINT_INDEX_LABEL_OFFSET: f64 = 12.;
|
||||
// Between a path's start anchor's point index and its path index, side by side
|
||||
pub const INDEX_LABEL_GAP: f64 = 8.;
|
||||
pub const PATH_FLOW_JOIN_TICK_LENGTH: f64 = 18.;
|
||||
pub const PATH_FLOW_JOIN_TICK_THICKNESS: f64 = 2.;
|
||||
|
||||
// CURVATURE COMB OVERLAY
|
||||
// A tooth's length in document pixels is the curvature times this scale, in square document pixels
|
||||
pub const CURVATURE_COMB_MIN_SCALE: f64 = 100.;
|
||||
pub const CURVATURE_COMB_MAX_SCALE: f64 = 10_000.;
|
||||
// Midway along its slider, at the geometric mean of the minimum and maximum
|
||||
pub const CURVATURE_COMB_DEFAULT_SCALE: f64 = 1000.;
|
||||
// In viewport pixels along each segment, until a segment reaches its maximum teeth
|
||||
pub const CURVATURE_COMB_TOOTH_SPACING: f64 = 6.;
|
||||
pub const CURVATURE_COMB_MAX_TEETH_PER_SEGMENT: f64 = 128.;
|
||||
// In viewport pixels, past which the teeth near a cusp would only streak across the screen
|
||||
pub const CURVATURE_COMB_MAX_TOOTH_LENGTH: f64 = 2000.;
|
||||
|
||||
// GRADIENT TOOL
|
||||
pub const GRADIENT_MIDPOINT_DIAMOND_RADIUS: f64 = 4.;
|
||||
pub const GRADIENT_MIDPOINT_MIN: f64 = 0.01;
|
||||
@@ -142,6 +176,11 @@ pub const ARC_SWEEP_GIZMO_RADIUS: f64 = 14.;
|
||||
pub const ARC_SWEEP_GIZMO_TEXT_HEIGHT: f64 = 12.;
|
||||
pub const GIZMO_HIDE_THRESHOLD: f64 = 20.;
|
||||
pub const GRID_ROW_COLUMN_GIZMO_OFFSET: f64 = 15.;
|
||||
pub const HEART_HANDLE_HOVER_RADIUS: f64 = 8.;
|
||||
/// How far the handles for the cleft's and tip's angles sit out along those tangents, in viewport pixels.
|
||||
pub const HEART_ANGLE_HANDLE_DISTANCE: f64 = 24.;
|
||||
/// How far a heart's Lobe Lean or Side Fullness handle is dragged to cross its whole range, in viewport pixels.
|
||||
pub const HEART_SLIDER_DRAG_DISTANCE: f64 = 200.;
|
||||
|
||||
// SCROLLBARS
|
||||
pub const SCROLLBAR_SPACING: f64 = 0.1;
|
||||
@@ -159,6 +198,7 @@ pub const COLOR_OVERLAY_GREEN: &str = "#63ce63";
|
||||
pub const COLOR_OVERLAY_GREEN_25: &str = "#63ce6340";
|
||||
pub const COLOR_OVERLAY_RED: &str = "#ef5454";
|
||||
pub const COLOR_OVERLAY_RED_25: &str = "#ef545440";
|
||||
pub const COLOR_OVERLAY_MAGENTA: &str = "#ba57bc";
|
||||
pub const COLOR_OVERLAY_GRAY: &str = "#cccccc";
|
||||
pub const COLOR_OVERLAY_GRAY_25: &str = "#cccccc40";
|
||||
pub const COLOR_OVERLAY_WHITE: &str = "#ffffff";
|
||||
@@ -177,6 +217,8 @@ pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
/// How far, in viewport pixels, the second press of a double-click can land from the first, and how far the first can travel before its release.
|
||||
pub const DOUBLE_CLICK_ALLOWED_TRAVEL: f64 = 4.;
|
||||
/// Maximum duration of the whole double-tap gesture, measured from the first tap's key-down to the second tap's key-up.
|
||||
pub const DOUBLE_TAP_MILLISECONDS: u64 = 1000;
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
|
||||
NodeGraphMessageDiscriminant::UpdateLayerPanel,
|
||||
))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
|
||||
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
|
||||
NodeGraphMessageDiscriminant::UpdateVisibleNodes,
|
||||
))),
|
||||
@@ -290,7 +291,6 @@ impl Dispatcher {
|
||||
preferences: &self.message_handlers.preferences_message_handler,
|
||||
current_tool: &self.message_handlers.tool_message_handler.tool_state.tool_data.active_tool_type,
|
||||
tool_edit_target: &self.message_handlers.tool_message_handler.edit_target,
|
||||
current_tool_icon: self.message_handlers.tool_message_handler.active_tool_icon(),
|
||||
reset_node_definitions_on_open: self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open,
|
||||
timing_information: self.message_handlers.animation_message_handler.timing_information(),
|
||||
animation: &self.message_handlers.animation_message_handler,
|
||||
@@ -305,8 +305,6 @@ impl Dispatcher {
|
||||
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
|
||||
@@ -16,5 +16,4 @@ pub enum AppWindowMessage {
|
||||
Hide,
|
||||
HideOthers,
|
||||
ShowAll,
|
||||
TmpToggleHideUI,
|
||||
}
|
||||
@@ -63,19 +63,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
responses.add(FrontendMessage::WindowRestart);
|
||||
}
|
||||
AppWindowMessage::TmpToggleHideUI => {
|
||||
responses.add(FrontendMessage::TmpToggleHideUI);
|
||||
responses.add(WorkspaceMessage::ToggleFocusDocument);
|
||||
responses.add(DeferMessage::AfterGraphRun {
|
||||
messages: vec![
|
||||
DocumentMessage::ZoomCanvasToFitAll.into(),
|
||||
DeferMessage::AfterGraphRun {
|
||||
messages: vec![DocumentMessage::ZoomCanvasToFitAll.into()],
|
||||
}
|
||||
.into(),
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
advertise_actions!(AppWindowMessageDiscriminant;
|
||||
@@ -86,7 +73,6 @@ impl MessageHandler<AppWindowMessage, ()> for AppWindowMessageHandler {
|
||||
Drag,
|
||||
Hide,
|
||||
HideOthers,
|
||||
TmpToggleHideUI,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,11 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
}));
|
||||
}
|
||||
|
||||
let copies = chain_nodes
|
||||
// The dots on wires between the copied chain nodes go along with them, so pasting them loose keeps those wires
|
||||
let chain_nodes_with_dots = active_document.network_interface.selection_with_bridging_dots(chain_nodes, &[]);
|
||||
let other_nodes = other_nodes.into_iter().filter(|node_id| !chain_nodes_with_dots.contains(node_id)).collect::<Vec<_>>();
|
||||
|
||||
let copies = chain_nodes_with_dots
|
||||
.iter()
|
||||
.filter_map(|node_id| active_document.network_interface.copy_chain_node(node_id, &[]))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, Dialog)]
|
||||
@@ -12,6 +13,11 @@ pub enum DialogMessage {
|
||||
PreferencesDialog(PreferencesDialogMessage),
|
||||
|
||||
// Messages
|
||||
Display {
|
||||
title: String,
|
||||
icon: IconName,
|
||||
},
|
||||
Redisplay,
|
||||
Dismiss,
|
||||
Close,
|
||||
CloseAndThen {
|
||||
|
||||
@@ -15,6 +15,7 @@ pub struct DialogMessageContext<'a> {
|
||||
#[derive(Debug, Default, Clone, ExtractField)]
|
||||
pub struct DialogMessageHandler {
|
||||
on_dismiss: Option<Message>,
|
||||
redisplay: Option<Message>,
|
||||
export_dialog: ExportDialogMessageHandler,
|
||||
new_document_dialog: NewDocumentDialogMessageHandler,
|
||||
preferences_dialog: PreferencesDialogMessageHandler,
|
||||
@@ -30,6 +31,21 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||
|
||||
DialogMessage::Display { title, icon } => {
|
||||
self.redisplay = Some(
|
||||
DialogMessage::Display {
|
||||
title: title.clone(),
|
||||
icon: icon.clone(),
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
responses.add(FrontendMessage::DisplayDialog { title, icon });
|
||||
}
|
||||
DialogMessage::Redisplay => {
|
||||
if let Some(message) = self.redisplay.clone() {
|
||||
responses.add(message);
|
||||
}
|
||||
}
|
||||
DialogMessage::Dismiss => {
|
||||
if let Some(message) = self.on_dismiss.take() {
|
||||
responses.add(message);
|
||||
@@ -37,6 +53,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
}
|
||||
DialogMessage::Close => {
|
||||
self.on_dismiss = None;
|
||||
self.redisplay = None;
|
||||
responses.add(FrontendMessage::DialogClose)
|
||||
}
|
||||
DialogMessage::CloseAndThen { followups } => {
|
||||
@@ -134,6 +151,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
}
|
||||
DialogMessage::RequestPreferencesDialog => {
|
||||
self.on_dismiss = Some(PreferencesDialogMessage::Confirm.into());
|
||||
self.redisplay = Some(DialogMessage::RequestPreferencesDialog.into());
|
||||
self.preferences_dialog.send_dialog_to_frontend(responses, preferences);
|
||||
}
|
||||
DialogMessage::RequestConfirmRestartDialog { preferences_requiring_restart } => {
|
||||
|
||||
@@ -85,7 +85,7 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| FrontendMessage::DialogClose.into()).widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! Dialogs are represented as structs that implement the `DialogLayoutHolder` trait.
|
||||
//!
|
||||
//! To open a dialog, call the function `send_dialog_to_frontend()` on the dialog struct.
|
||||
//! Then dialog can be opened by sending the `FrontendMessage::DisplayDialog` message;
|
||||
//! Then dialog can be opened by sending the `DialogMessage::Display` message;
|
||||
|
||||
mod dialog_message;
|
||||
mod dialog_message_handler;
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ impl DialogLayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| FrontendMessage::DialogClose.into()).widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
|
||||
+41
-54
@@ -361,49 +361,43 @@ impl PreferencesDialogMessageHandler {
|
||||
// COMPATIBILITY
|
||||
// =============
|
||||
{
|
||||
let wgpu_available = graph_craft::application_io::wgpu_available().unwrap_or(false);
|
||||
let is_desktop = cfg!(not(target_family = "wasm"));
|
||||
if wgpu_available || is_desktop {
|
||||
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
|
||||
rows.push(header);
|
||||
}
|
||||
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
|
||||
|
||||
if wgpu_available {
|
||||
let render_tile_resolution_description = "
|
||||
Maximum X or Y resolution per render tile. Larger tiles may improve performance but can cause flickering or missing content in complex artwork if set too high.\n\
|
||||
\n\
|
||||
*Default: 1280 px.*
|
||||
"
|
||||
.trim();
|
||||
let render_tile_resolution_label = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("Render Tile Resolution")
|
||||
.tooltip_label("Render Tile Resolution")
|
||||
.tooltip_description(render_tile_resolution_description)
|
||||
.widget_instance(),
|
||||
];
|
||||
let render_tile_resolution = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(preferences.max_render_region_size as f64))
|
||||
.tooltip_label("Render Tile Resolution")
|
||||
.tooltip_description(render_tile_resolution_description)
|
||||
.mode_range()
|
||||
.int()
|
||||
.min(256.)
|
||||
.max(4096.)
|
||||
.increment_step(256.)
|
||||
.unit(" px")
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
let size = number_input.value.unwrap_or(EditorPreferences::default().max_render_region_size as f64) as u32;
|
||||
PreferencesMessage::MaxRenderRegionSize { size }.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
];
|
||||
let render_tile_resolution_description = "
|
||||
Maximum X or Y resolution per render tile. Larger tiles may improve performance but can cause flickering or missing content in complex artwork if set too high.\n\
|
||||
\n\
|
||||
*Default: 1280 px.*
|
||||
"
|
||||
.trim();
|
||||
let render_tile_resolution_label = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("Render Tile Resolution")
|
||||
.tooltip_label("Render Tile Resolution")
|
||||
.tooltip_description(render_tile_resolution_description)
|
||||
.widget_instance(),
|
||||
];
|
||||
let render_tile_resolution = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(preferences.max_render_region_size as f64))
|
||||
.tooltip_label("Render Tile Resolution")
|
||||
.tooltip_description(render_tile_resolution_description)
|
||||
.mode_range()
|
||||
.int()
|
||||
.min(256.)
|
||||
.max(4096.)
|
||||
.increment_step(256.)
|
||||
.unit(" px")
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
let size = number_input.value.unwrap_or(EditorPreferences::default().max_render_region_size as f64) as u32;
|
||||
PreferencesMessage::MaxRenderRegionSize { size }.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
rows.extend_from_slice(&[render_tile_resolution_label, render_tile_resolution]);
|
||||
}
|
||||
rows.extend_from_slice(&[header, render_tile_resolution_label, render_tile_resolution]);
|
||||
|
||||
if is_desktop {
|
||||
let ui_acceleration_description = "
|
||||
@@ -411,7 +405,7 @@ impl PreferencesDialogMessageHandler {
|
||||
\n\
|
||||
Disabling UI acceleration may slightly degrade performance, so this should be used as a workaround only if issues are observed with displaying the UI. This setting may become enabled automatically if Graphite launches, detects that it cannot draw the UI normally, and restarts in compatibility mode.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
*Default: On.*
|
||||
"
|
||||
.trim();
|
||||
|
||||
@@ -422,14 +416,11 @@ impl PreferencesDialogMessageHandler {
|
||||
CheckboxInput::new(preferences.disable_ui_acceleration)
|
||||
.tooltip_label("Disable UI Acceleration")
|
||||
.tooltip_description(ui_acceleration_description)
|
||||
.on_update(|number_input: &CheckboxInput| Message::Batched {
|
||||
messages: Box::new([
|
||||
PreferencesDialogMessage::MayRequireRestart.into(),
|
||||
PreferencesMessage::DisableUIAcceleration {
|
||||
disable_ui_acceleration: number_input.checked,
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
.on_update(|number_input: &CheckboxInput| {
|
||||
PreferencesMessage::DisableUIAcceleration {
|
||||
disable_ui_acceleration: number_input.checked,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.for_label(checkbox_id)
|
||||
.widget_instance(),
|
||||
@@ -448,8 +439,6 @@ impl PreferencesDialogMessageHandler {
|
||||
let vsync_description = "
|
||||
Render frames with vertical synchronization (v-sync) to prevent visual tearing within Graphite and the operating system compositor. This introduces increased input latency which is more noticeable on lower refresh rate displays. Future versions of Graphite will aim to reduce the macOS-specific latency without tearing artifacts.\n\
|
||||
\n\
|
||||
The application will restart for this change to take effect.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
@@ -463,9 +452,7 @@ impl PreferencesDialogMessageHandler {
|
||||
CheckboxInput::new(vsync_checked)
|
||||
.tooltip_label("Enable V-Sync")
|
||||
.tooltip_description(vsync_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| Message::Batched {
|
||||
messages: Box::new([PreferencesDialogMessage::MayRequireRestart.into(), PreferencesMessage::VSync { vsync: checkbox_input.checked }.into()]),
|
||||
})
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::VSync { vsync: checkbox_input.checked }.into())
|
||||
.for_label(checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Enable V-Sync")
|
||||
|
||||
@@ -13,7 +13,7 @@ impl DialogLayoutHolder for AboutGraphiteDialog {
|
||||
const TITLE: &'static str = "About Graphite";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
|
||||
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| DialogMessage::Close.into()).widget_instance()];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
|
||||
Loaded 100 of 388 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user