mirror of
https://github.com/storytold/figcraft.git
synced 2026-11-30 10:16:46 +01:00
Merge remote-tracking branch 'origin/main' into fix/2179-property-defaults-follow-main
# Conflicts: # crates/engine/src/assets/components.rs # crates/engine/src/assets/components/diff.rs # docs/components-parity.md
This commit is contained in:
commit
87eccbb067
470 files changed
+26507
-2516
No files matched your search
@@ -4,10 +4,10 @@
|
||||
"repository_id": 1412112308,
|
||||
"producer_workflow_id": 429731005,
|
||||
"producer_workflow_path": ".github/workflows/nightly.yml",
|
||||
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"producer_tooling_revision": "main",
|
||||
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
|
||||
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
|
||||
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
|
||||
"signer_tooling_revision": "main",
|
||||
"release_branch": "nightly-signer",
|
||||
"manual_actors": [
|
||||
"bflatastic",
|
||||
@@ -28,7 +28,7 @@
|
||||
"workflow_path": ".github/workflows/ci.yml",
|
||||
"jobs": [
|
||||
{
|
||||
"name": "gate / gate (ubuntu-24.04)",
|
||||
"name": "gate / gate (artcraft-k8s-main)",
|
||||
"app_id": 15368,
|
||||
"applicability": "required"
|
||||
}
|
||||
@@ -95,7 +95,15 @@
|
||||
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
|
||||
"trust": {
|
||||
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
|
||||
}
|
||||
},
|
||||
"package_formats": [
|
||||
"appimage",
|
||||
"arch",
|
||||
"deb",
|
||||
"flatpak",
|
||||
"oci",
|
||||
"rpm"
|
||||
]
|
||||
},
|
||||
"macos-aarch64": {
|
||||
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
|
||||
|
||||
@@ -8,21 +8,24 @@ workflows:
|
||||
'.github/workflows/house-rules.yml': []
|
||||
'.github/workflows/lockfile.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
'.github/workflows/nightly-macos.yml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/upload-artifact@v7.0.2'
|
||||
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
- 'storytold/craft-common-actions@f5141455aac7b2eb4708aa259d8ffcdf10fde939'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
- 'storytold/craft-common-actions@main'
|
||||
'.github/workflows/nightly-sign.yml': []
|
||||
'.github/workflows/nightly.yml': []
|
||||
'.github/workflows/nix.yml': []
|
||||
'.github/workflows/notify-services.yml': []
|
||||
'.github/workflows/packaging-lint.yml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.22.4'
|
||||
'.github/workflows/release.yml': []
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
'.github/workflows/release.yml':
|
||||
- 'actions/checkout@v7.0.1'
|
||||
- 'step-security/harden-runner@v2.23.0'
|
||||
'.github/workflows/sonarcloud.yml': []
|
||||
'.github/workflows/windows-arm64.yml': []
|
||||
dependencies:
|
||||
@@ -46,14 +49,14 @@ dependencies:
|
||||
commit: 'sha1-8dd607977d06adf4ed49b190381e74c17a9dd25f'
|
||||
owner_id: 88700172
|
||||
repo_id: 1249865941
|
||||
'step-security/harden-runner@v2.22.4':
|
||||
ref: 'v2.22.4'
|
||||
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
|
||||
'step-security/harden-runner@v2.23.0':
|
||||
ref: 'v2.23.0'
|
||||
commit: 'sha1-aebdcf6156ab6691adf63218240e476564a1ed4c'
|
||||
owner_id: 88700172
|
||||
repo_id: 422287306
|
||||
'storytold/craft-common-actions@f5141455aac7b2eb4708aa259d8ffcdf10fde939':
|
||||
'storytold/craft-common-actions@main':
|
||||
ref: 'main'
|
||||
commit: 'sha1-f5141455aac7b2eb4708aa259d8ffcdf10fde939'
|
||||
commit: 'sha1-bc70e5d7f90828265b20708399a2265e62b9b7d6'
|
||||
owner_id: 76897702
|
||||
repo_id: 1414429108
|
||||
uses:
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
RUST_BACKTRACE: 1
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
@@ -45,12 +45,12 @@ jobs:
|
||||
# The same craft-fonts commit the Nightly producer pins (nightly.yml craft-fonts-ref), so the
|
||||
# bundle's notices and fonts match a shipped build.
|
||||
- name: Check out craft-fonts
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main
|
||||
with:
|
||||
ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
- uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main
|
||||
- id: rust
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@f5141455aac7b2eb4708aa259d8ffcdf10fde939
|
||||
uses: storytold/craft-common-actions/actions/rust-channel@main
|
||||
with:
|
||||
targets: aarch64-apple-darwin
|
||||
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
|
||||
|
||||
@@ -34,12 +34,26 @@ jobs:
|
||||
checks: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: figcraft
|
||||
producer_run_id: ${{ inputs.producer_run_id }}
|
||||
producer_run_attempt: ${{ inputs.producer_run_attempt }}
|
||||
secrets:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
|
||||
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
|
||||
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
|
||||
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
|
||||
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
|
||||
# No secrets: inherit or raw platform values in this caller. Only the isolated native
|
||||
# callee job may bind the release environment and export its keys; that environment must
|
||||
# admit nightly-signer alongside release before the first dispatch.
|
||||
@@ -22,9 +22,9 @@ jobs:
|
||||
actions: read
|
||||
attestations: write
|
||||
id-token: write
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
|
||||
with:
|
||||
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
|
||||
tooling-revision: main
|
||||
app-name: figcraft
|
||||
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
@@ -32,3 +32,4 @@ jobs:
|
||||
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
|
||||
# #369 and #364).
|
||||
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
|
||||
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
|
||||
@@ -48,7 +48,7 @@ jobs:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.22.4
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
|
||||
@@ -14,9 +14,7 @@ on:
|
||||
type: string
|
||||
default: ""
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
@@ -29,14 +27,35 @@ jobs:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
uses: storytold/craft-common-actions/.github/workflows/refresh-contributors.yml@main
|
||||
# The DMG round trip with an ad-hoc signed fixture (#387): no signing secrets.
|
||||
dmg-test:
|
||||
name: macOS DMG integrity
|
||||
runs-on: macos-15
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Harden runner
|
||||
uses: step-security/harden-runner@v2.23.0
|
||||
with:
|
||||
egress-policy: audit
|
||||
- uses: actions/checkout@v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Test signed fixture and installation copy
|
||||
run: bash packaging/macos/dmg-test.sh
|
||||
release:
|
||||
needs: credits
|
||||
needs: [credits, dmg-test]
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
|
||||
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
|
||||
with:
|
||||
dry-run: ${{ github.event_name == 'schedule' }}
|
||||
app-name: figcraft
|
||||
app-title: FigCraft
|
||||
macos-runner: macos-15
|
||||
# Combined Latin presentation and core UI catalog. Required web builds enforce
|
||||
# Inter Regular/SemiBold and Noto Sans Georgian Regular after asset-policy filtering.
|
||||
craft-fonts-ref: 37827adc41fd165f9a9234ac40f94dbad353aa69
|
||||
|
||||
@@ -17,7 +17,7 @@ concurrency:
|
||||
jobs:
|
||||
sonarcloud:
|
||||
# Pin the coverage setup that provisions test data and fetches locked dependencies before offline metadata tests.
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@5008f8cd1b011b35eed223a7d058d7a8e9075ef6
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
# The shared coverage archive's shards omit the CLI executable used by integration tests.
|
||||
# Run this repository's suite in one instrumented job and provide its pinned test data.
|
||||
|
||||
@@ -67,7 +67,7 @@ FigCraft is an open-source, pure-Rust (egui) design app (Figma-class): interface
|
||||
|
||||
### Layout
|
||||
- `crates/*` by layer, enforced by `cargo xtask layers`: geom and color (L0), doc (L1), layout, text, pathops, plugin, collab (L2), render and format (L3), svg, pdf and vectordrawable (L4), engine (L5), ui-egui, mcp and collab-net (L6), then `apps/`. Nothing below L6 depends on egui, eframe, rfd or winit, so the UI crate is swappable.
|
||||
- Commands live in `crates/engine/src/cmd/*` (`spec!(id, label, params doc, undoable, run)`). Menus, shortcuts, the Actions palette, CLI, control channel and MCP dispatch the same ids. The menu catalog is `crates/engine/src/catalog.rs` (`cargo xtask parity`). A programmatic call only requests UI (`Session::request_ui`); the control channel drops dialog requests.
|
||||
- Commands live in `crates/engine/src/cmd/*` (`spec!(id, label, params doc, undoable, run)`). Menus, shortcuts, the Actions palette, CLI, control channel and MCP dispatch the same ids. The menu catalog is `crates/engine/src/catalog.rs` (`cargo xtask parity`). Its headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)) is computed: an item is `headless: yes` only when its id is in the engine registry (`find_command`), never through a UI-layer id. A counted item with no engine command gets a `no`/`partial` mark with a `window`, `os` or `engine-gap` reach in `HEADLESS` in the same file, or shows as `unknown`. Never write `yes` there, and drop the mark when the command lands (stale marks fail the tests). A programmatic call only requests UI (`Session::request_ui`); the control channel drops dialog requests.
|
||||
- Panels read engine state and act through `app.run(id, params)` or `app.set_props(ids, props)`. Colours come from `theme::Tokens`.
|
||||
- Progress docs: `ROADMAP.md`, `docs/gaps.md` (ranked work list), `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/architecture.md`, the `docs/*-parity.md` files and the generated `docs/parity-checklist.md`. A PR that lands a task updates the rows it touches.
|
||||
- Releases: `docs/releasing.md`. Control protocol: `docs/control-protocol.md`. MCP: `docs/mcp.md`.
|
||||
|
||||
Generated
+630
-149
File diff suppressed because it is too large.
Load diff
+54
-42
@@ -6,17 +6,17 @@ exclude = ["plugins"]
|
||||
# default-members = ["crates/*", "apps/figcraft", "apps/figcraft-cli", "xtask"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.18.1"
|
||||
version = "0.19.0"
|
||||
edition = "2024"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.95"
|
||||
repository = "https://github.com/storytold/figcraft"
|
||||
|
||||
[workspace.dependencies]
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false, features = ["tree"] }
|
||||
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-pdf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-xml = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", default-features = false, features = ["tree"] }
|
||||
craft-vectordrawable = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-pdf = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# internal
|
||||
figcraft-geom = { path = "crates/geom" }
|
||||
figcraft-color = { path = "crates/color" }
|
||||
@@ -39,44 +39,54 @@ figcraft-plugin = { path = "crates/plugin" }
|
||||
|
||||
# Keep every craft-libs crate on one rev.
|
||||
# Which paths stored in a document may be followed (craft-libs).
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# Who draws the window frame on Linux — the compositor or the app — so every Craft app shows the
|
||||
# same native titlebar per desktop (craft-libs). FigCraft reads the probe result and maps it to its
|
||||
# own `TitleBar`; the UI runtime takes its window system from here too.
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# The control channel's token files and the AI agents link through the ArtCraft Launcher's switch:
|
||||
# the connection file the app publishes and the `figcraft-cli mcp` side that finds the open window
|
||||
# (craft-libs; #2740).
|
||||
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", features = ["agents"] }
|
||||
# craft-update: app-specific pretend versions apply to startup and manual checks.
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
|
||||
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", features = ["ui"] }
|
||||
# The suite's font store: exact lookup of a missing font in the pinned Google Fonts and Noto
|
||||
# indexes, and checksum-verified installs into the one folder every Craft app reads (craft-libs).
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-font-store = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# The UI runtime FigCraft's egui UI is hosted by (`crates/ui-egui/src/framework.rs`) and the
|
||||
# framework dialogs on it (craft-libs): who the app is to those dialogs, the runtime's key
|
||||
# bindings, the theme mode and the interface direction.
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-host = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# The macOS app menu whose Quit (⌘Q) asks the app before quitting, like the window's close button
|
||||
# (craft-libs; the menu it replaces quits straight through `terminate:` and loses unsaved work).
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# Where the settings live: the suite's folder rules, portable mode included (craft-libs).
|
||||
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-settings = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
|
||||
# Penpot export container only; JSON values cross this boundary, not shared model types.
|
||||
craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-penpot = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
|
||||
# The design-file formats (craft-libs): the .fig container and its kiwi encoding, the mapping of
|
||||
# a .fig message onto the REST file JSON, and that JSON's shared helpers.
|
||||
craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["frames"] }
|
||||
craft-sketch = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-fig = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-figcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-figma-rest = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-jpeg = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
# Camera raw files (craft-libs): the container decoders, and the shared develop stages that turn
|
||||
# sensor data into a picture (demosaic, white balance, colour matrices, tone).
|
||||
craft-raw = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-color-transform = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-geom = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", features = ["frames"] }
|
||||
|
||||
# foundation
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
@@ -115,9 +125,11 @@ icu_segmenter = { version = "2.3", default-features = false, features = ["compil
|
||||
# dependencies, BSD-3-Clause, no_std so the web build keeps it too).
|
||||
deunicode = "1.6"
|
||||
linesweeper = "0.5"
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
zip = { version = "=9.8.2", default-features = false, features = ["deflate-flate2"] }
|
||||
# `.fig` import: raw deflate chunks (already built for zip) and zstd chunks (pure Rust, MIT, wasm-safe).
|
||||
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||
brotli = { version = "9", default-features = false, features = ["std"] }
|
||||
brotli-decompressor = { version = "6", default-features = false, features = ["std"] }
|
||||
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
|
||||
sha1 = "0.11"
|
||||
sha2 = "0.10"
|
||||
@@ -196,22 +208,22 @@ opt-level = 3
|
||||
|
||||
# Keep the complete egui family and native event bridge on reviewed fork commits.
|
||||
[patch.crates-io]
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
|
||||
ecolor = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
emath = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" }
|
||||
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
|
||||
|
||||
# craft-libs' vendored krilla 0.8.2: decoded PNGs are capped at 1 GiB and reserved fallibly, and a
|
||||
# panic while drawing unwinds without aborting.
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf" }
|
||||
@@ -208,7 +208,7 @@ exposes to agents, and exported at 2x by FigCraft's own renderer. The source fil
|
||||
</td>
|
||||
<td width="50%" valign="top">
|
||||
<h3>Prototype and hand off</h3>
|
||||
Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like <code>count + 1</code>), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF.
|
||||
Connections, triggers, actions and Smart Animate-style transitions, variables with conditionals (if / else if / else built in the interaction editor, expressions like <code>count + 1</code>), flows, a presentation view with device frames, hotspot hints and an Inspect panel, and a live preview pane. Alt to measure distances and padding on the canvas, Inspect mode with measurements, annotations in colour-coded categories, a ready-for-dev list with a focus view and Compare changes (before / after with property-level diffs since a frame was marked ready), and code (CSS, HTML, React, Vue, Leptos, SwiftUI, Compose, ArkUI, Flutter, Uno C# Markup) where components take their properties as parameters, comment threads pinned to frames (replies, @mentions, reactions, read state) and named version history. Export any layer at any scale to PNG, JPG, WebP, SVG or PDF.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
+9
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~26 points and ~162–292 h away (one Opus 5.5 agent; ~33–67 h wall-clock with 5 agents)
|
||||
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the document compressed to clients that read it, about seven times smaller (#1665); a control request that times out says truthfully whether it was dropped or is still running and will take effect, and only screenshots and input blame the window (#1673); a board keeps earlieLine truncated
|
||||
> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-19 · **Change:** minor (macOS DMGs are built with `hdiutil create -fs HFS+` and the app is verified in the finished image and an installation copy (#387); variables export and import as DTCG design tokens (#1687); Uno C# Markup code generation for layers, with auto layout and vectors as paths; M5: prototype arrow-key aliases and explicit document-scoped player controls, including batch rollback; numbers unchanged; M9: clients accept complete legacy welcomes without a reconnect secret and re-authenticate on reconnect (#2365); a boolean group takes a corner radius (and smoothing) that rounds every sharp corner of its result (#2222); a text style binds a number variable to its weight (#2174); mind maps, first step: a first node with three children on curved branches, laid out again after every edit (`board.mindMap`, `board.mindMapAdd`, #2226); the handoff mode reads Developer Mode in the interface, its ids and saved fields unchanged; the left rail's and tab strip's icons are larger, 20 pt (#553); Suggest auto layout adds nested auto layout frames by rows and columns and keeps the placement of the design, as the help center describes (#1823); the Local variables window selects several variables (click, Shift+click for a range, Cmd/Ctrl+click to toggle, Escape to clear) and delete, move to a group and scope act on the selected local variables in one undo step (#2002); the desktop UI takes a system face for Ethiopic, Devanagari, Gurmukhi, Gujarati, Tamil, Telugu, Kannada and Malayalam, Sinhala, Lao, Myanmar, Khmer, Armenian and Georgian as it did for Hebrew and Arabic, so a String variable's Amharic value draws in the panels instead of boxes (#2014); a layer's effect binding takes only a field its effect has; ; the boolean operation menu leads each entry with an original icon (#2003); glass takes one sample instead of its dispersion window where the colours split under 1/256 px; glass bends towards its core, and rounded rectangles work it out in closed form; glass's light is a line on its bevel and splay turns the bend towards the centre; glass bends with a thick-lens profile and splits its colours over 8 steps; glass effects take variables and keep their frost within 0–100; web host bridge: `?host=parent` or `data-host="page"` hands a page the app's files, documented in the hosting guide; a connector end moved with Cmd/Ctrl held goes on any part of an object, and stays there as the object moves or resizes; a tap on a plugin panel's button keeps what was typed in its fields; a Dash cap setting (none, round or square) on Dash and Custom strokes, drawn on both ends of every dash; library analytics list how many layers and files use each style and variable; the Controller menu names each button as PlayStation and Switch controllers do; widgets draw lines and SVG pictures (plugin API 6); a connector end dropped along a side of a shape attaches to that side (#1708); regression tests pin a rounded shape's one-sided stroke and SVG ids and font families without XML-forbidden characters (#1351, #1124); a damaged image is refused with a reason instead of showing as an empty box (#1474); an image copied in another app pastes again on the desktop, and in the browser for the first time (#492); SwiftUI and Compose code names a bound variable by its iOS or Android code syntax; the colour picker's Image tab shows a placeholder and Upload from computer, an asset preview, and a file dropped on it replaces the image, keeping the fill mode, crop and position (#1682); the Frame tool's Phone presets have the iPhone 17 family (#1691); Show in folder works in the Flatpak build and selects the file on Linux (#1701); a dashed line starts and ends with a half-length dash, on the canvas and in exports; the Pages, Layers and Assets search fields keep their text in the middle of the field (#1703); a board connector's path can be reshaped by dragging its path handles (#1710); boards have 16 more shapes (arrows, polygons, star, plus and flowchart symbols), in pickers that lay them out in a grid; library analytics count insertions and show insertions and detachments over the past 30 days, 90 days or year; a stroke's Custom style takes a dash pattern of any length as a comma-separated list (#1681); a control request can set its own timeout, up to 10 minutes (`timeoutMs`; `figcraft-cli mcp --attach PORT --timeout SECONDS`) (#1696); gap 6: a widget opens its plugin's panel (plugin API 5), whose callbacks redraw it; the keyboard's Menu key opens the context menu, as Shift+F10 does; an Open link action can open in place of the prototype, with "Open in new tab" off (gap 15); a collection of this file can be extended (Extend collection on its row, `variable.extendCollection`), its extension following its edits at once, and extended collections extend again in the file; the eyedropper with Cmd/Ctrl+Shift makes a colour style or variable of what it picks; a live session's welcome sends the Line truncated
|
||||
|
||||
FigCraft is a clean-room, open-source, pure-Rust reimplementation of the Figma design workflow,
|
||||
native on macOS, Windows, Linux and FreeBSD and in the browser, fully drivable by agents through
|
||||
@@ -366,6 +366,10 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-11-28 | minor | M8: the MCP prompt `implement_design` takes an agent through building the selected design in a codebase: `design_context` for what the designer set, connected components reused through `component_mappings` and `sync_mappings`, tokens before literal values, real files from `export_assets`, the annotations and `responsive` for what the design states beyond its size, and `compare_design` to check the result. With nothing selected it asks which frame to build, and it reports what it approximated, assumed or couldn't check. A test now checks that every tool and result field the server instructions and prompts name exists, as one already did for command ids. Numbers unchanged |
|
||||
| 2026-11-28 | minor | M1, #2185: `node.create` (and the MCP `create_node` tool) takes `children`, a list of `node.create` params made inside the new layer, each with children of its own, in one command and one undo step. The result mirrors the tree (`{id, children: [{id, children?}, …]}`), so a batch step names any layer in it with a `field` path; a refused child names its place (`children[1].children[0]: …`) and nothing is made. A card or a dialog is one call instead of a step per layer. Tests: `node_create_tree_tests`. Numbers unchanged. |
|
||||
| 2026-11-28 | minor | M7, #1687: variables export and import as DTCG design tokens (format 2025.10), the files token build pipelines read. `variable.export {format: "dtcg", mode?}` (also Variables ▸ Export… ▸ Design tokens (DTCG)…, saved as `.tokens.json`) writes a group per collection and a token per variable, nested by the `/` parts of its name: colours as `colorSpace`/`components`/`alpha` objects (with `hex` in sRGB, `display-p3` in a Display P3 file), numbers as px dimensions or plain numbers where layers use them unitless, aliases as `{group.token}` (one leaving the exported collections as the value it shows), colour calculations as the colour they show; strings and booleans, which DTCG has no type for, every mode's value and the variable's scopes go under `$extensions` (`ai.storyteller.figcraft`), and `mode` picks which mode is `$value`. `variable.import` reads a file holding a `$value` as tokens: each top-level group a collection (top-level tokens one named Tokens), types handed down from groups, `color` (object or `#hex`), `dimension` (px, rem at 16 px, or the older `16px` string), `number`, `fontWeight` (number or name), `duration` (ms), `fontFamily`, strings, booleans and aliases (an untyped alias takes its target's type); without our modes a collection fills the default mode of this file's collection of its name. Composite tokens (typography, shadows and the like) are skipped and counted in the warnings, never dropped silently. Tests: `dtcg_tests` (format, three) and `variables_io_tests::design_tokens_export_and_import_round_trip`, `plain_design_tokens_update_the_default_mode` (engine). Numbers unchanged |
|
||||
| 2026-11-27 | minor | M8: visual verification for agents. `inspect.compare` and the MCP tool `compare_design` compare a capture of a built page, made by the agent's own browser tools, with a frame, on this computer: the layers that differ, deepest and largest first, each a position (with its offset), colour (expected and actual) or content difference, with text held to twice the tolerance. A retina capture is the same design. Numbers unchanged. Tests: `visual_compare_tests`, MCP `compare_design`. |
|
||||
| 2026-11-26 | minor | #1396, craft-contrib#95: `figcraft-cli` follows RFC-0018. The CLI is a library with `run(args, out, err)` (`main` is a thin wrapper), failures are typed errors (exit 1, usage errors exit 2), output goes through the caller's writers, a closed stdout is quiet, `-V` works after subcommands, `FIGCRAFT_NO_SYSTEM_FONTS` and `FIGCRAFT_SERVER_KEY` are declared on `--no-system-fonts` and `plugin publish --key`, the packages install the man pages and Bash, Zsh and Fish completions (Linux and FreeBSD). Changed behaviour: `convert`/`run` refuse an output that is the input unless `--in-place` is given (it needs `--in`/`--out`); `export -o` and `render -o` refuse the file they read; `plugin publish` accepts `--key`; a blank `FIGCRAFT_NO_SYSTEM_FONTS` counts as unset and an unrecognised value is a usage error. Tests in `apps/figcraft-cli/tests/it/rfc18.rs`. Numbers unchanged |
|
||||
| 2026-11-24 | minor | M7: New York, Apple's serif that macOS installs as the hidden `.New York`, is found and listed under its public name (it was a missing font). Numbers unchanged. |
|
||||
| 2026-11-15 | patch | Removed the obsolete duplicate live-session bullet from the browser crate docs; the existing server publishing and remote wss guidance remains authoritative. Runtime behavior unchanged. |
|
||||
@@ -378,6 +382,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-11-18 | minor | M8: asset handoff. `file.exportAssets` and the MCP tool `export_assets` write a design's images and vectors into a folder: images as the file's original bytes, never re-encoded, vectors as SVG, layers with export settings by those settings, each saying which it is. Files are named by their content, so an asset has one file and exporting again writes nothing; what a layer does to an image that isn't in its bytes is listed. Numbers unchanged |
|
||||
| 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 2 of 4): mind maps in the UI. The Shapes flyout ends in a mind map tool (`tool.mindMap`): a click places a map with the first node's text starting there and types in it. Cmd/Ctrl+Enter adds a child of the selected or edited node (`board.mindMapAdd`), Shift+Cmd/Ctrl+Enter its next sibling (`board.nextSticky` on a node), both typing on; Tab and Shift+Tab walk a node's siblings in the map's order (`select.next`, `select.previous`). The bar over the selection colours a node's text (`board.setColor`) and shows a branch the connector's controls without the line types. Tests: `board_mindmap_tests` (four more), `board_ui_tests` (five more). Breadth ~47% → ~48%, ready ~29% → ~30%. |
|
||||
| 2026-11-10 | minor | M7, #2173: `variable.export {format: "json"}` writes a top-level `textStyles` array beside `meta` (each text style as `style.list {type: "text"}` returns it; `bound` holds the ids `meta.variables` is keyed by for variables of the exported collections, so an export filtered by `collections` can name variables it doesn't include), and `variable.import` reads it back (styles merged by name, bindings re-pointed; a binding to a variable the JSON lacks is kept without a warning when the existing style already holds that same variable, and otherwise dropped with a warning). A FigCraft extension: the REST `styles` metadata has no values. CSS, Tailwind and Dart stay variables-only |
|
||||
| 2026-11-15 | patch | CLI usage and operation failures escape terminal controls in paths and error text, using the same printable-text rule as info and script diagnostics; exit codes and ordinary quotes and paths stay unchanged. |
|
||||
| 2026-11-10 | minor | Experimental `.fig` export preserves set-variable, set-variable-mode and conditional prototype actions (#2210). |
|
||||
| 2026-11-15 | patch | Document HTTP(S) links without a host are refused before opening; regressions retain valid query, fragment, IPv6 and mail links. |
|
||||
@@ -385,6 +390,8 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-11-15 | patch | CLI export and render help and docs name the existing first non-divider page default, including the all-divider fallback and explicit page selection. Behavior unchanged. |
|
||||
| 2026-11-15 | patch | CLI export and render reject repeated scale suffixes such as `2xx` as usage errors (exit 2); numeric values and one optional `x` suffix retain the existing limits. |
|
||||
| 2026-11-16 | patch | M9, #2365: native and browser clients accept the complete legacy `Welcome` layout without its later reconnect secret, preserving explicit access and rejecting incomplete or trailing data. A host that supplies no secret is rejoined with the share link instead of an unauthenticated `Resume`. Numbers unchanged. |
|
||||
| 2026-11-14 | minor | M6: Uno C# Markup code, auto layout and vectors (ours): a frame with horizontal or vertical auto layout is a Toolkit `AutoLayout` that takes the box itself (`Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with `Orientation`, `Spacing`, `Padding` (less the stroke weight unless strokes are included; where that goes negative the border sits behind the layout in a `Grid`), `PrimaryAxisAlignment`, `CounterAxisAlignment` and `Justify`; children are sized per axis (fixed writes the length, hug none, fill stretches with the attached `AutoLayout` call, min and max lengths on the child), text hugs, fills or is fixed, a child that ignores the layout is independent at its offset (a hugging parent with one is written at its size), the exported frame itself hugs where it hugs in the design, a clip is written only on a frame fixed on both axes, and `reverse_z` paints with descending `Canvas.ZIndex`; grid mode is a `Grid` with `ColumnDefinitions` / `RowDefinitions` (pixels, `Auto`, whole-number stars), `ColumnSpacing` / `RowSpacing`, children in the cell the layout crate gives them (`.Grid(row:, column:, rowSpan:, columnSpan:)`) aligned in it; wrap is one line with a note; frames without auto layout keep the `Canvas` with one warning per view that counts them; an explicit line height moves the text down by the half-leading of the face FigCraft draws with (a top padding with a negative bottom margin in a panel, the offset in a `Canvas`; the number depends on the fonts installed where `inspect.code` runs; a line height below the font's natural height keeps `LineHeight` and adds `LineStackingStrategy.BlockLineHeight`); vectors, booleans and shapes are a `Microsoft.UI.Xaml.Shapes.Path` with path data (`F1` non-zero, `F0` even-odd; at most 5,000 elements), one solid fill and one solid stroke, falling back to a PNG `Image` for gradients, several paints, effects and over the cap; containers are locals and children go in with `Children.Add(x)` / `Child = x`, since fluent `.Children(…)` doubles the load time with every level of nesting. Numbers unchanged (the incumbent has no such target). |
|
||||
| 2026-11-10 | minor | M6: Uno Platform C# Markup code (ours; the incumbent generates CSS, iOS and Android only): `inspect.code {language: uno}` (aliases `csharp-markup`, `cs-markup`) writes a `UserControl` class whose content is a fluent C# Markup tree for a layer: a frame, group or rectangle is a `Border` (fill as `Color.FromArgb`, border brush and thickness, per-side thickness, per-corner radius, opacity, rotation) holding a `Canvas` with the children at their offsets (a stroke and children put the border behind the canvas in a `Grid`, so the stroke does not push the children in), an ellipse is an `Ellipse`, text is a `TextBlock` (family, size, weight, italic, colour, line height, character spacing, alignment, wrapping, trimming and max lines from the auto resize mode, decoration, case applied when the code runs, mixed styles as `Run`s) and vectors and other shapes are an `Image` on an SVG asset (`ms-appx:///Assets/<name>.svg`, a lowercase ASCII name unique in the snippet) with a comment to export it; image fills are an `ImageBrush` on a PNG asset. Fixed sizes everywhere; auto layout, variables, components and the project export are later steps. Shadows, blurs, blend modes, gradients beyond the first stop, masks and corner smoothing stay as `// not mapped: …` comments in the chain. Not offered for code connect or component code yet. Headline numbers unchanged. |
|
||||
| 2026-11-10 | minor | M4, #2222: a boolean group takes a corner radius that rounds every sharp corner of its result. Numbers unchanged |
|
||||
| 2026-11-10 | minor | M12, #2226 (step 1 of 4): mind maps in the document and engine. `board.mindMap` places a first node with three children on curved branches and `board.mindMapAdd` adds a child or a sibling; the normalize pass lays a touched map out again from its first node (88 between columns, 48 between siblings, stacks centred on their parents). No toolbar entry yet; numbers unchanged. |
|
||||
| 2026-11-07 | patch | M10, #1902: web builds with craft-fonts embed Noto Sans Arabic Regular by default, so Persian and Arabic text has a fallback without `FIGCRAFT_EMBED_SCRIPTS=Arab`; required web builds reject catalogs without that face. Web faces are compressed losslessly at build time and restored once at runtime to keep the default catalog within the WASM size budget. A decode failure logs the unavailable face once; a compiler regression checks generated catalog initialization. Additional scripts remain opt-in. Exact Iran Sans appearance still needs the installed font through supported browsers' local font access. Numbers unchanged. |
|
||||
@@ -620,6 +627,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md).
|
||||
| 2026-10-15 | minor | Drop files anywhere to open them (M7): dragging files over the window shows a "Drop to open" (home) or "Drop to import" (canvas) overlay. On the home screen each supported file opens as a document of its own and other files are turned away with a toast; on the canvas the files import at the drop point. Both wait behind a small card that is on screen before a large file blocks the window. A canvas import stays with the document and page that received the drop even if the tab or page changes meanwhile, and is cancelled with a message if that document or page is gone. Numbers unchanged. |
|
||||
| 2026-10-15 | minor | M7: system font discovery skips entries observed as non-regular files before opening them, avoiding the reproduced named-pipe stall. Regular-file symlinks remain supported; directory depth, font limits and priorities are unchanged. Numbers unchanged. |
|
||||
| 2026-10-15 | minor | Canvas retains a bounded margin while panning so newly exposed strips can reuse the previous render. Numbers unchanged. |
|
||||
| 2026-10-15 | minor | macOS DMG: replace the HFS hybrid image builder that adds FinderInfo after signing; verify the app in the finished read-only image and a normal installation copy, with notarization checks for signed releases. A separate release-workflow job runs the native ad-hoc regression once before the shared release job, covering signature integrity and cleanup (#387). Numbers unchanged. |
|
||||
| 2026-10-15 | minor | Dev Mode tail (M6, gap 16): import lines for connected components inside generated layer trees (definitions, slots and swapped-in instances too); `dev.compare {version}` and the compare view's Compare with menu compare with any saved version; behaviour suite (5 tests; 4 failed before the fixes): an inspect-only Dev Mode canvas with menus, shortcuts, nudges, opacity keys and paste refusing design edits, toolbar drawing tools returning to the design, Changed in the ready list (`inspect.readyForDev {status: changed}`), statuses only on sections and top-level frames; read-only plugins' panels from the Inspect tab. Dev Mode 96%/72% → 97%/76%, 0–1 h → 2–4 h (measurements kept on the canvas and a read-only layers panel counted as missing); header totals not recomputed |
|
||||
| 2026-10-15 | minor | Typography spacing icons scrub with the shared number-field gesture, modifier rates and one Undo step per drag (#373). Units and selected-character targeting are preserved. Numbers unchanged. |
|
||||
| 2026-10-14 | minor | System theme on first run (M7): preferences without a theme default to System; the first frame reads the OS appearance directly, including when returning from a manual theme. Saved Light/Dark choices stay explicit; unavailable OS appearance falls back to Light. Numbers unchanged. |
|
||||
|
||||
@@ -19,12 +19,17 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
figcraft-engine = { workspace = true }
|
||||
figcraft-collab-net = { workspace = true }
|
||||
figcraft-doc = { workspace = true }
|
||||
figcraft-render = { workspace = true }
|
||||
figcraft-text = { workspace = true }
|
||||
figcraft-svg = { workspace = true }
|
||||
figcraft-format = { workspace = true }
|
||||
figcraft-mcp = { workspace = true }
|
||||
# `mcp`: the open window through the ArtCraft Launcher's switch, and the control channel's token.
|
||||
craft-control = { workspace = true }
|
||||
# The settings folder the app publishes its connection file in.
|
||||
craft-settings = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -14,7 +14,8 @@ use figcraft_doc::{PrintSettings, VdCompat};
|
||||
///
|
||||
/// Files: .figcraft (native), .penpot (Penpot 2.x), .json (FigCraft or REST API file JSON), .fig
|
||||
/// (best effort; `info` lists what wasn't imported), .sketch (Sketch 48 or newer, best effort),
|
||||
/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer).
|
||||
/// .svg, .png/.jpg/.webp/.gif/.bmp (open as an image layer), camera raw files such as .rw2, .cr2,
|
||||
/// .cr3, .nef, .arw, .raf, .orf and .dng (developed as shot into an image layer).
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "figcraft-cli",
|
||||
@@ -124,6 +125,10 @@ pub struct ExportArgs {
|
||||
/// (exact) or dropped without notes (ignore)
|
||||
#[arg(long, value_name = "bestEffort|exact|ignore", value_parser = vd_compat, default_value = "bestEffort")]
|
||||
pub vd_compat: VdCompat,
|
||||
/// Write nothing and fail (exit 1, listing why) when the export would leave out or change
|
||||
/// content. For fig, penpot and xml, the formats that report what they can't hold
|
||||
#[arg(long)]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -156,6 +161,10 @@ pub struct ConvertArgs {
|
||||
/// Allow OUT to be the file IN, replacing it
|
||||
#[arg(long)]
|
||||
pub in_place: bool,
|
||||
/// Write nothing and fail (exit 1, listing why) when OUT would leave out or change content.
|
||||
/// For .fig and .penpot, which report what they can't hold, and .figcraft, which holds everything
|
||||
#[arg(long)]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -196,6 +205,10 @@ pub struct RunArgs {
|
||||
/// Allow --out to be the --in file, replacing it
|
||||
#[arg(long, requires_all = ["input", "out"])]
|
||||
pub in_place: bool,
|
||||
/// Write nothing and fail (exit 1, listing why) when --out would leave out or change content.
|
||||
/// For .fig and .penpot, which report what they can't hold, and .figcraft, which holds everything
|
||||
#[arg(long, requires = "out")]
|
||||
pub strict: bool,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -211,20 +224,29 @@ pub struct CommandsArgs {
|
||||
pub filter: Option<String>,
|
||||
}
|
||||
|
||||
/// Serve MCP on stdio: headless, or attached to a running app
|
||||
/// Serve MCP on stdio: the open app, headless, or attached to a running app
|
||||
///
|
||||
/// The automation roots confine the headless session's file access. A server started with
|
||||
/// --attach is confined by the app it attaches to: start that app with `figcraft --control PORT`
|
||||
/// and the same roots.
|
||||
/// While the ArtCraft Launcher's AI agents switch lets agents use FigCraft, each call goes to the
|
||||
/// open FigCraft window (started when it is closed), otherwise to a session without a window, which
|
||||
/// uses the automation roots or else the agent folders. Without the switch, the automation roots
|
||||
/// confine the headless session's file access and are required. A server started with --attach is
|
||||
/// confined by the app it attaches to: start that app with `figcraft --control PORT` and the same
|
||||
/// roots.
|
||||
#[derive(Args)]
|
||||
pub struct McpArgs {
|
||||
/// Attach to the app started with `figcraft --control PORT`; a bare port means 127.0.0.1:PORT.
|
||||
/// Refuses the automation roots
|
||||
#[arg(long, value_name = "PORT", value_parser = attach, conflicts_with_all = ["automation_read_root", "automation_write_root"])]
|
||||
pub attach: Option<String>,
|
||||
/// Never use the open app: a session without a window, confined to the automation roots
|
||||
#[arg(long, conflicts_with = "attach")]
|
||||
pub headless: bool,
|
||||
/// How long the attached app may take over each request, in seconds (1–600; default 60)
|
||||
#[arg(long, value_name = "SECONDS", requires = "attach", value_parser = clap::value_parser!(u64).range(1..=600))]
|
||||
pub timeout: Option<u64>,
|
||||
/// Allow a confined headless MCP session to join collaboration links from this server (repeatable)
|
||||
#[arg(long = "automation-allow-server", value_name = "URL", conflicts_with = "attach")]
|
||||
pub automation_allow_servers: Vec<String>,
|
||||
#[command(flatten)]
|
||||
pub roots: RootArgs,
|
||||
}
|
||||
@@ -570,6 +592,7 @@ mod tests {
|
||||
(&["mcp", "--attach", "7979", "--timeout", "601"], ValueValidation),
|
||||
(&["mcp", "--timeout", "300"], MissingRequiredArgument),
|
||||
(&["mcp", "--attach", "7979", "--automation-read-root", "."], ArgumentConflict),
|
||||
(&["mcp", "--attach", "7979", "--automation-allow-server", "wss://figcraft.example.com/"], ArgumentConflict),
|
||||
(&["mcp", "--automation-write-root"], InvalidValue),
|
||||
(&["mcp", "stray"], UnknownArgument),
|
||||
(&["convert", "a"], MissingRequiredArgument),
|
||||
@@ -603,6 +626,7 @@ mod tests {
|
||||
assert_eq!(e.as_ref().map(clap::Error::kind), Some(ErrorKind::DisplayHelp), "{args:?}");
|
||||
assert_eq!(e.map(|e| e.exit_code()), Some(0), "{args:?}");
|
||||
}
|
||||
|
||||
// The help is the subcommand's, even after a mistake.
|
||||
let help = try_parse(&["plugin", "publish", "--bogus", "--help"]).err().map(|e| e.to_string()).unwrap_or_default();
|
||||
assert!(help.contains("Usage: figcraft-cli plugin publish"), "{help}");
|
||||
@@ -611,6 +635,23 @@ mod tests {
|
||||
assert_eq!(a.file, "-h");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_accepts_repeated_server_allowlists() {
|
||||
let Command::Mcp(a) = ok(&[
|
||||
"mcp",
|
||||
"--automation-read-root",
|
||||
"in",
|
||||
"--automation-write-root",
|
||||
"out",
|
||||
"--automation-allow-server",
|
||||
"wss://figcraft.example.com/",
|
||||
"--automation-allow-server=wss://team.example.com/design/",
|
||||
]) else {
|
||||
panic!("mcp")
|
||||
};
|
||||
assert_eq!(a.automation_allow_servers, ["wss://figcraft.example.com/", "wss://team.example.com/design/"]);
|
||||
}
|
||||
|
||||
/// Every subcommand's help renders and documents each of its options.
|
||||
#[test]
|
||||
fn every_subcommand_has_help() {
|
||||
|
||||
@@ -113,8 +113,39 @@ fn encode(doc: &Document, pix: &figcraft_render::Pixmap, e: &str) -> CliResult<V
|
||||
figcraft_render::encode_export(pix, format, doc.color_profile).map_err(CliError::Failed)
|
||||
}
|
||||
|
||||
/// Write `doc` to `out`, choosing the format by extension.
|
||||
pub fn write_doc(doc: &Document, page: NodeId, out: &str, io: &mut Io) -> CliResult<()> {
|
||||
/// Whether `export` to `out` (in `format`, else by its extension) reports what it leaves out, so
|
||||
/// `--strict` has something to hold it to.
|
||||
pub(crate) fn export_reports_losses(format: Option<&str>, out: &str) -> bool {
|
||||
let format = format.map_or_else(|| ext(out), str::to_ascii_lowercase);
|
||||
matches!(format.as_str(), "fig" | "penpot" | "xml")
|
||||
}
|
||||
|
||||
/// Whether `export` to `out` (in `format`, else by its extension) writes Android Vector Drawables.
|
||||
pub(crate) fn export_writes_xml(format: Option<&str>, out: &str) -> bool {
|
||||
format.map_or_else(|| ext(out), str::to_ascii_lowercase) == "xml"
|
||||
}
|
||||
|
||||
/// Whether writing a document to `out` reports what it leaves out (.fig, .penpot) or keeps
|
||||
/// everything (.figcraft), so `--strict` has something to hold it to.
|
||||
pub(crate) fn save_reports_losses(out: &str) -> bool {
|
||||
matches!(ext(out).as_str(), "figcraft" | "fig" | "penpot")
|
||||
}
|
||||
|
||||
/// What writing `out` left out or changed: a note each on stderr or, when `strict`, the failure that
|
||||
/// keeps `out` from being written.
|
||||
fn notes(out: &str, warnings: Vec<String>, strict: bool, io: &mut Io) -> CliResult<()> {
|
||||
if strict && !warnings.is_empty() {
|
||||
return Err(CliError::Failed(format!("{out} wasn't written (--strict): the export would leave out or change: {}", warnings.join("; "))));
|
||||
}
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `doc` to `out`, choosing the format by extension. `strict`: fail, writing nothing, when
|
||||
/// the format would leave something out.
|
||||
pub fn write_doc(doc: &Document, page: NodeId, out: &str, strict: bool, io: &mut Io) -> CliResult<()> {
|
||||
let e = ext(out);
|
||||
let bytes = match e.as_str() {
|
||||
"figcraft" => {
|
||||
@@ -130,27 +161,24 @@ pub fn write_doc(doc: &Document, page: NodeId, out: &str, io: &mut Io) -> CliRes
|
||||
.into_bytes(),
|
||||
"png" | "jpg" | "jpeg" | "webp" => encode(doc, &render_page(doc, page, 1.0)?, &e)?,
|
||||
"pdf" => page_pdf(doc, page, &PrintSettings::default())?,
|
||||
"fig" => fig_bytes(doc, io)?,
|
||||
"penpot" => penpot_bytes(doc, io)?,
|
||||
"fig" => fig_bytes(doc, out, strict, io)?,
|
||||
"penpot" => penpot_bytes(doc, out, strict, io)?,
|
||||
other => return Err(CliError::Usage(format!("unknown output format `.{other}` (figcraft, json, svg, png, jpg, webp, pdf, fig, penpot)"))),
|
||||
};
|
||||
write(out, &bytes)
|
||||
}
|
||||
|
||||
/// `doc` as a `.fig` file (experimental), printing what was left out.
|
||||
fn fig_bytes(doc: &Document, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
/// `doc` as a `.fig` file (experimental) for `out`, with [`notes`] on what was left out.
|
||||
fn fig_bytes(doc: &Document, out: &str, strict: bool, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::fig_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
notes(out, warnings, strict, io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn penpot_bytes(doc: &Document, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
/// `doc` as a Penpot archive for `out`, with [`notes`] on what was left out.
|
||||
fn penpot_bytes(doc: &Document, out: &str, strict: bool, io: &mut Io) -> CliResult<Vec<u8>> {
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::penpot_bytes(doc).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
notes(out, warnings, strict, io)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
@@ -259,18 +287,20 @@ pub struct Target {
|
||||
pub print: PrintSettings,
|
||||
/// Android Vector Drawable (XML) only.
|
||||
pub vd_compat: VdCompat,
|
||||
/// Fail, writing nothing, when the export would leave something out (`.fig`, `.penpot` and XML).
|
||||
pub strict: bool,
|
||||
}
|
||||
|
||||
pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32> {
|
||||
let doc = load(file, io)?;
|
||||
// `.fig`: the whole file.
|
||||
if t.format.as_deref().map_or(ext(out) == "fig", |f| f.eq_ignore_ascii_case("fig")) {
|
||||
write(out, &fig_bytes(&doc, io)?)?;
|
||||
write(out, &fig_bytes(&doc, out, t.strict, io)?)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
if t.format.as_deref().map_or(ext(out) == "penpot", |f| f.eq_ignore_ascii_case("penpot")) {
|
||||
write(out, &penpot_bytes(&doc, io)?)?;
|
||||
write(out, &penpot_bytes(&doc, out, t.strict, io)?)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
@@ -283,26 +313,26 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
};
|
||||
let target = node.map(|q| find_node(&doc, page, q)).transpose()?;
|
||||
let single = image_format(&ext(out)).is_some();
|
||||
let mut bytes_of = |ids: &[NodeId]| {
|
||||
// The bytes and what an Android Vector Drawable changed or left out, like the .fig notes.
|
||||
let bytes_of = |ids: &[NodeId]| {
|
||||
let setting = ExportSetting { format: fmt, print: *print, vd_compat: t.vd_compat, ..Default::default() };
|
||||
let (bytes, warnings) = figcraft_engine::cmd::file::export_file(&doc, ids, &setting, scale).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
// What an Android Vector Drawable changed or left out, like the .fig notes.
|
||||
for w in warnings {
|
||||
errln!(io, "note: {w}");
|
||||
}
|
||||
Ok::<_, CliError>(bytes)
|
||||
figcraft_engine::cmd::file::export_file(&doc, ids, &setting, scale).map_err(|e| CliError::Failed(e.to_string()))
|
||||
};
|
||||
if single {
|
||||
let bytes = match target {
|
||||
let (bytes, warnings) = match target {
|
||||
Some(t) => bytes_of(&[t])?,
|
||||
None if fmt == ExportFormat::Pdf => page_pdf(&doc, page, print)?,
|
||||
None if fmt == ExportFormat::Pdf => (page_pdf(&doc, page, print)?, Vec::new()),
|
||||
None => bytes_of(&children(&doc, page))?,
|
||||
};
|
||||
notes(out, warnings, t.strict, io)?;
|
||||
write(out, &bytes)?;
|
||||
outln!(io, "{out}");
|
||||
return Ok(0);
|
||||
}
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
// `--strict` writes the folder only once every file in it is known to leave nothing out.
|
||||
if !t.strict {
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
}
|
||||
let ids = match target {
|
||||
Some(t) => vec![t],
|
||||
None => {
|
||||
@@ -314,6 +344,7 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
if ids.is_empty() {
|
||||
return Err(CliError::Failed("the page is empty: nothing to export".into()));
|
||||
}
|
||||
let (mut pending, mut left_out) = (Vec::new(), Vec::new());
|
||||
let mut used = std::collections::BTreeSet::new();
|
||||
let mut next_suffix: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for id in ids {
|
||||
@@ -329,9 +360,28 @@ pub fn export(file: &str, out: &str, t: &Target, io: &mut Io) -> CliResult<i32>
|
||||
}
|
||||
};
|
||||
let path = Path::new(out).join(format!("{name}.{}", fmt.ext())).to_string_lossy().into_owned();
|
||||
write(&path, &bytes_of(&[id])?)?;
|
||||
let (bytes, warnings) = bytes_of(&[id])?;
|
||||
if t.strict {
|
||||
for w in warnings {
|
||||
if !left_out.contains(&w) {
|
||||
left_out.push(w);
|
||||
}
|
||||
}
|
||||
pending.push((path, bytes));
|
||||
continue;
|
||||
}
|
||||
notes(&path, warnings, false, io)?;
|
||||
write(&path, &bytes)?;
|
||||
outln!(io, "{path}");
|
||||
}
|
||||
if t.strict {
|
||||
notes(out, left_out, true, io)?;
|
||||
figcraft_engine::file_access::create_dir_all(out).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
for (path, bytes) in pending {
|
||||
write(&path, &bytes)?;
|
||||
outln!(io, "{path}");
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
@@ -354,7 +404,7 @@ fn refuse_dropping_images_from_script(input: Option<(&str, usize)>, active: &fig
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn convert(input: &str, out: &str, io: &mut Io) -> CliResult<i32> {
|
||||
pub fn convert(input: &str, out: &str, strict: bool, io: &mut Io) -> CliResult<i32> {
|
||||
let (loaded, _) = figcraft_engine::cmd::file::load_path(input, None).map_err(|e| CliError::Failed(format!("can't open {input}: {e}")))?;
|
||||
refuse_dropping_images(input, out, loaded.images_past_budget)?;
|
||||
if ext(input) == "penpot" {
|
||||
@@ -368,7 +418,7 @@ pub fn convert(input: &str, out: &str, io: &mut Io) -> CliResult<i32> {
|
||||
.filter(|p| doc.pages.contains(p))
|
||||
.or_else(|| doc.first_page())
|
||||
.ok_or_else(|| CliError::Failed("the document has no pages".into()))?;
|
||||
write_doc(&doc, page, out, io)?;
|
||||
write_doc(&doc, page, out, strict, io)?;
|
||||
outln!(io, "{out}");
|
||||
Ok(0)
|
||||
}
|
||||
@@ -423,7 +473,7 @@ pub fn parse_script(text: &str) -> Result<Vec<BatchStep>, String> {
|
||||
/// file is refused before it is read (#1114).
|
||||
pub const MAX_SCRIPT: u64 = 1 << 30;
|
||||
|
||||
pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, io: &mut Io) -> CliResult<i32> {
|
||||
pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, strict: bool, io: &mut Io) -> CliResult<i32> {
|
||||
let bytes = figcraft_engine::file_access::read_capped(script, MAX_SCRIPT).map_err(|e| CliError::Failed(e.to_string()))?;
|
||||
let text = String::from_utf8(bytes).map_err(|_| CliError::Failed(format!("{script}: not UTF-8")))?;
|
||||
let steps = parse_script(&text).map_err(|e| CliError::Failed(format!("{script}: {e}")))?;
|
||||
@@ -470,7 +520,7 @@ pub fn run_script(script: &str, input: Option<&str>, out: Option<&str>, io: &mut
|
||||
// Through the engine, so the version history is kept.
|
||||
write(out, &figcraft_engine::cmd::file::file_bytes_at(ds, out).map_err(|e| CliError::Failed(e.to_string()))?)?;
|
||||
} else {
|
||||
write_doc(&ds.doc, ds.page, out, io)?;
|
||||
write_doc(&ds.doc, ds.page, out, strict, io)?;
|
||||
}
|
||||
errln!(io, "wrote {out}");
|
||||
}
|
||||
@@ -525,7 +575,7 @@ mod tests {
|
||||
std::fs::write(&svg, r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>"#).unwrap();
|
||||
std::fs::write(&script, r#"[{"command":"no.such\u001b"}]"#).unwrap();
|
||||
assert_eq!(info(svg.to_str().unwrap(), false, io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, None, io!()).unwrap(), 1);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, None, false, io!()).unwrap(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -610,7 +660,7 @@ mod tests {
|
||||
for ext in ["svg", "pdf"] {
|
||||
let path = dir.join(format!("previous.{ext}"));
|
||||
std::fs::write(&path, b"previous export").unwrap();
|
||||
let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap(), io!()).unwrap_err() else {
|
||||
let CliError::Failed(error) = write_doc(&doc, page, path.to_str().unwrap(), false, io!()).unwrap_err() else {
|
||||
panic!("depth overflow must be an operation failure");
|
||||
};
|
||||
assert!(error.contains("maximum export depth of 256"), "{ext}: {error}");
|
||||
@@ -637,7 +687,7 @@ mod tests {
|
||||
bad.push("/dev/zero".into());
|
||||
}
|
||||
for path in bad {
|
||||
let Err(CliError::Failed(e)) = run_script(&path, None, None, io!()) else { panic!("{path} ran") };
|
||||
let Err(CliError::Failed(e)) = run_script(&path, None, None, false, io!()) else { panic!("{path} ran") };
|
||||
assert!(e.contains("is a folder, not a file") || e.contains("isn't a regular file"), "{path}: {e}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
@@ -695,7 +745,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 0);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -725,7 +775,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 0);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 0);
|
||||
|
||||
let mut s = Session::empty();
|
||||
s.execute("file.open", &json!({"path": out.to_str().unwrap()})).unwrap();
|
||||
@@ -742,7 +792,7 @@ mod tests {
|
||||
let dir = temp_dir("run-dup-name");
|
||||
let script = dir.join("script.json");
|
||||
std::fs::write(&script, r#"[{"command": "select.none", "as": "a"}, {"command": "select.none", "as": "a"}]"#).unwrap();
|
||||
let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None, io!()) else { panic!("a name twice must fail") };
|
||||
let Err(CliError::Failed(e)) = run_script(script.to_str().unwrap(), None, None, false, io!()) else { panic!("a name twice must fail") };
|
||||
assert!(e.contains("step 1: `as` \"a\" is already step 0's name"), "{e}");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -762,7 +812,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let out = dir.join("out.figcraft");
|
||||
// The failure is the script's, not the call's: the CLI reports it and exits non-zero.
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), io!()).unwrap(), 1);
|
||||
assert_eq!(run_script(script.to_str().unwrap(), None, Some(out.to_str().unwrap()), false, io!()).unwrap(), 1);
|
||||
assert!(!out.exists(), "a script that failed writes nothing");
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
+211
-16
@@ -26,12 +26,13 @@ macro_rules! errln {
|
||||
|
||||
mod args;
|
||||
mod files;
|
||||
mod live;
|
||||
mod perf;
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
|
||||
use args::{Cli, Command, ConnectCommand, PluginCommand, RootArgs};
|
||||
use args::{Cli, Command, ConnectCommand, McpArgs, PluginCommand, RootArgs};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The automation roots a file subcommand was given, if any. Omitting both leaves the run
|
||||
@@ -76,6 +77,13 @@ pub type CliResult<T> = Result<T, CliError>;
|
||||
|
||||
fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
|
||||
check(&cli.command)?;
|
||||
// Headless MCP is always confined (AGENTS.md: agent entry points refuse to start without both
|
||||
// roots, unless the ArtCraft Launcher's switch lets agents in, which gives them the agent
|
||||
// folders); checked before the fonts are scanned, so a usage error comes back at once.
|
||||
let mcp_plan = match &cli.command {
|
||||
Command::Mcp(a) => Some(mcp_plan(a, &live::launcher_allows)?),
|
||||
_ => None,
|
||||
};
|
||||
if !cli.no_system_fonts {
|
||||
// Text lays out with the installed fonts, like the desktop app, so headless renders and
|
||||
// auto layout sizes match what users see.
|
||||
@@ -87,19 +95,26 @@ fn dispatch(cli: Cli, io: &mut Io) -> CliResult<i32> {
|
||||
match cli.command {
|
||||
Command::Info(a) => confined(&a.roots, || files::info(&a.file, a.json, io)),
|
||||
Command::Export(a) => {
|
||||
let target =
|
||||
files::Target { print: a.print(), vd_compat: a.vd_compat, scale: a.scale.scale, format: a.format, page: a.page, node: a.node };
|
||||
let target = files::Target {
|
||||
print: a.print(),
|
||||
vd_compat: a.vd_compat,
|
||||
scale: a.scale.scale,
|
||||
format: a.format,
|
||||
page: a.page,
|
||||
node: a.node,
|
||||
strict: a.strict,
|
||||
};
|
||||
confined(&a.roots, || files::export(&a.file, &a.out, &target, io))
|
||||
}
|
||||
Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, io)),
|
||||
Command::Convert(a) => confined(&a.roots, || files::convert(&a.input, &a.output, a.strict, io)),
|
||||
Command::Render(a) => confined(&a.roots, || files::render(&a.file, &a.out, a.scale.scale, a.page.as_deref(), io)),
|
||||
Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), io)),
|
||||
Command::Run(a) => confined(&a.roots, || files::run_script(&a.script, a.input.as_deref(), a.out.as_deref(), a.strict, io)),
|
||||
Command::Commands(a) => {
|
||||
commands(a.json, a.filter.as_deref(), io);
|
||||
Ok(0)
|
||||
}
|
||||
// `--attach` conflicts with the roots: the app runs the commands, only its own roots can confine them.
|
||||
Command::Mcp(a) => mcp(a.attach.as_deref(), a.timeout, roots_of(&a.roots)?, io),
|
||||
Command::Mcp(_) => mcp(mcp_plan.ok_or_else(|| CliError::Failed("no MCP plan".into()))?, io),
|
||||
Command::Plugin { command: PluginCommand::Publish(a) } => publish_plugin(&a.folder, &a.server, a.key.as_deref(), io),
|
||||
Command::Connect { command: ConnectCommand::Publish(a) } => {
|
||||
confined(&a.roots, || files::connect_publish(&a.file, &a.mappings, a.dry_run, io))
|
||||
@@ -157,17 +172,60 @@ fn publish_plugin(folder: &str, server: &str, key: Option<&str>, io: &mut Io) ->
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
fn mcp(attach: Option<&str>, timeout: Option<u64>, roots: Option<figcraft_engine::file_access::Roots>, io: &mut Io) -> CliResult<i32> {
|
||||
let backend: Box<dyn figcraft_mcp::Backend> = match attach {
|
||||
Some(addr) => {
|
||||
let no_app = |e: std::io::Error| format!("can't reach the FigCraft app at {addr}: {e} (start it with `figcraft --control PORT`)");
|
||||
let b = figcraft_mcp::Attached::connect(addr).map_err(no_app)?;
|
||||
match timeout {
|
||||
Some(secs) => Box::new(b.with_timeout(std::time::Duration::from_secs(secs)).map_err(no_app)?),
|
||||
None => Box::new(b),
|
||||
}
|
||||
/// How `figcraft-cli mcp` serves.
|
||||
enum McpPlan {
|
||||
/// `--attach ADDR`: the app started with `--control`, its token read from the file it wrote.
|
||||
Attach { addr: String, timeout: Option<std::time::Duration> },
|
||||
/// No window: `--headless`, or the ArtCraft Launcher's switch doesn't let agents use FigCraft.
|
||||
Headless(figcraft_engine::file_access::Roots),
|
||||
/// The open window while the launcher's switch lets agents in, otherwise headless (#2740).
|
||||
Live(live::Options),
|
||||
}
|
||||
|
||||
/// What `a` asks for. `allowed` reads the launcher's switch; it is asked only when it decides
|
||||
/// (no `--attach`, no `--headless`).
|
||||
fn mcp_plan(a: &McpArgs, allowed: &dyn Fn() -> bool) -> CliResult<McpPlan> {
|
||||
let timeout = a.timeout.map(std::time::Duration::from_secs);
|
||||
if let Some(addr) = &a.attach {
|
||||
return Ok(McpPlan::Attach { addr: addr.clone(), timeout });
|
||||
}
|
||||
let config_dir = live::settings_dir();
|
||||
match config_dir {
|
||||
Some(config_dir) if !a.headless && allowed() => {
|
||||
let servers = allowed_servers(&a.automation_allow_servers)?;
|
||||
let path = |d: &String| std::path::PathBuf::from(d);
|
||||
let launch = std::env::current_exe().ok().and_then(|cli| craft_control::agents::launcher(&cli, "figcraft"));
|
||||
Ok(McpPlan::Live(live::Options {
|
||||
config_dir,
|
||||
read_roots: a.roots.automation_read_root.iter().map(path).collect(),
|
||||
write_roots: a.roots.automation_write_root.iter().map(path).collect(),
|
||||
servers,
|
||||
timeout,
|
||||
launch,
|
||||
consent: Box::new(live::launcher_allows),
|
||||
}))
|
||||
}
|
||||
None => Box::new(figcraft_mcp::Headless::new()),
|
||||
_ => Ok(McpPlan::Headless(mcp_roots(&a.roots, &a.automation_allow_servers)?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn mcp(plan: McpPlan, io: &mut Io) -> CliResult<i32> {
|
||||
let (backend, roots): (Box<dyn figcraft_mcp::Backend>, _) = match plan {
|
||||
McpPlan::Attach { addr, timeout } => {
|
||||
let no_app = |e: std::io::Error| format!("can't reach the FigCraft app at {addr}: {e} (start it with `figcraft --control PORT`)");
|
||||
let mut b = figcraft_mcp::Attached::connect(&addr).map_err(no_app)?;
|
||||
if let Some(token) = attach_token(&addr, &live::control_app()) {
|
||||
b = b.with_token(token);
|
||||
}
|
||||
let b = match timeout {
|
||||
Some(t) => b.with_timeout(t).map_err(no_app)?,
|
||||
None => b,
|
||||
};
|
||||
(Box::new(b), None)
|
||||
}
|
||||
McpPlan::Headless(roots) => (Box::new(figcraft_mcp::Headless::new()), Some(roots)),
|
||||
// Each route confines itself: the window by the app's own roots, a headless session by its folders.
|
||||
McpPlan::Live(options) => (Box::new(live::LiveBackend::new(options)), None),
|
||||
};
|
||||
errln!(io, "figcraft MCP server ({}) on stdio", backend.describe());
|
||||
if let Some(r) = &roots {
|
||||
@@ -180,6 +238,45 @@ fn mcp(attach: Option<&str>, timeout: Option<u64>, roots: Option<figcraft_engine
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// The token `--attach ADDR` sends: for a loopback address the token file the app on this machine
|
||||
/// wrote for that port (or `FIGCRAFT_CONTROL_TOKEN`); for any other host only
|
||||
/// `FIGCRAFT_CONTROL_TOKEN`, since this machine's token file belongs to this machine's app.
|
||||
fn attach_token(addr: &str, app: &craft_control::auth::App) -> Option<String> {
|
||||
let (host, port) = addr.rsplit_once(':')?;
|
||||
let port = port.parse::<u16>().ok()?;
|
||||
let host = host.trim_start_matches('[').trim_end_matches(']');
|
||||
let loopback = host.eq_ignore_ascii_case("localhost") || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
|
||||
if loopback { app.client_token(port, None).map(|t| t.token) } else { app.env_token() }
|
||||
}
|
||||
|
||||
/// The roots a headless MCP session is confined to: both kinds are required, and the servers in
|
||||
/// `allowed_servers` (ws:// or wss:// addresses without a query or key) are the only ones
|
||||
/// `collab.join` may reach.
|
||||
fn mcp_roots(roots: &RootArgs, allowed_servers: &[String]) -> CliResult<figcraft_engine::file_access::Roots> {
|
||||
if roots.automation_read_root.is_empty() || roots.automation_write_root.is_empty() {
|
||||
return Err(CliError::Usage("headless mcp requires both --automation-read-root and --automation-write-root".into()));
|
||||
}
|
||||
let roots = figcraft_engine::file_access::Roots::new(&roots.automation_read_root, &roots.automation_write_root).map_err(CliError::Failed)?;
|
||||
Ok(roots.with_allowed_servers(self::allowed_servers(allowed_servers)?))
|
||||
}
|
||||
|
||||
/// `--automation-allow-server`: ws:// or wss:// server URLs without a query or key.
|
||||
fn allowed_servers(allowed_servers: &[String]) -> CliResult<Vec<String>> {
|
||||
let mut servers = Vec::with_capacity(allowed_servers.len());
|
||||
for server in allowed_servers {
|
||||
if server.contains('?') {
|
||||
return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
|
||||
}
|
||||
let (endpoint, query) = figcraft_collab_net::Endpoint::parse(server)
|
||||
.map_err(|_| CliError::Usage("--automation-allow-server must be a ws:// or wss:// server URL".into()))?;
|
||||
if !query.is_empty() {
|
||||
return Err(CliError::Usage("--automation-allow-server must not contain a query or key".into()));
|
||||
}
|
||||
servers.push(endpoint.url());
|
||||
}
|
||||
Ok(servers)
|
||||
}
|
||||
|
||||
/// What the arguments can't say alone: an output that would replace its input needs `--in-place`.
|
||||
fn check(command: &Command) -> CliResult<()> {
|
||||
let refuse = |flag: &str, path: &str, input: &str, allowed: bool| -> CliResult<()> {
|
||||
@@ -191,6 +288,25 @@ fn check(command: &Command) -> CliResult<()> {
|
||||
}
|
||||
Err(CliError::Usage(format!("{flag} {path} is the input, which it would replace: choose another file, or pass --in-place")))
|
||||
};
|
||||
// `--strict` holds a writer to what it reports, so it is refused where nothing would be checked.
|
||||
let unchecked = |what: &str, formats: &str| {
|
||||
Err(CliError::Usage(format!("--strict checks {formats}, the formats that report what they leave out; {what} isn't one of them")))
|
||||
};
|
||||
match command {
|
||||
Command::Export(a) if a.strict && !files::export_reports_losses(a.format.as_deref(), &a.out) => {
|
||||
return unchecked(&format!("--out {}", a.out), "fig, penpot and xml exports");
|
||||
}
|
||||
Command::Export(a) if a.strict && a.vd_compat == figcraft_doc::VdCompat::Ignore && files::export_writes_xml(a.format.as_deref(), &a.out) => {
|
||||
return Err(CliError::Usage("--strict can't check --vd-compat ignore, which drops what it can't draw without saying so".into()));
|
||||
}
|
||||
Command::Convert(a) if a.strict && !files::save_reports_losses(&a.output) => {
|
||||
return unchecked(&format!("OUT {}", a.output), ".fig, .penpot and .figcraft output");
|
||||
}
|
||||
Command::Run(a) if a.strict && !a.out.as_deref().is_some_and(files::save_reports_losses) => {
|
||||
return unchecked(&format!("--out {}", a.out.as_deref().unwrap_or("")), ".fig, .penpot and .figcraft output");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match command {
|
||||
Command::Convert(a) => refuse("OUT", &a.output, &a.input, a.in_place)?,
|
||||
Command::Run(a) => {
|
||||
@@ -255,3 +371,82 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mcp_roots_tests {
|
||||
use super::{CliError, McpPlan, attach_token, mcp_plan, mcp_roots};
|
||||
use crate::args::{McpArgs, RootArgs};
|
||||
|
||||
fn args(attach: Option<&str>, headless: bool, read: &[&str], write: &[&str]) -> McpArgs {
|
||||
let own = |d: &[&str]| d.iter().map(|s| s.to_string()).collect();
|
||||
McpArgs {
|
||||
attach: attach.map(str::to_string),
|
||||
headless,
|
||||
timeout: None,
|
||||
automation_allow_servers: Vec::new(),
|
||||
roots: RootArgs { automation_read_root: own(read), automation_write_root: own(write) },
|
||||
}
|
||||
}
|
||||
|
||||
// #2740: plain `mcp` with the ArtCraft Launcher's switch on needs no roots (the agent folders
|
||||
// stand in); with it off, or with --headless, both roots are still required (rule 18).
|
||||
#[test]
|
||||
fn plain_mcp_without_roots_runs_only_while_the_launcher_lets_agents_in() {
|
||||
let on = || true;
|
||||
let off = || false;
|
||||
let never = || -> bool { panic!("the switch decides nothing here") };
|
||||
assert!(matches!(mcp_plan(&args(None, false, &[], &[]), &off), Err(CliError::Usage(_))));
|
||||
assert!(matches!(mcp_plan(&args(None, true, &[], &[]), &never), Err(CliError::Usage(_))), "--headless needs both roots");
|
||||
assert!(matches!(mcp_plan(&args(Some("127.0.0.1:7979"), false, &[], &[]), &never), Ok(McpPlan::Attach { .. })));
|
||||
// Needs a settings folder to find the app in; every test machine has a platform folder.
|
||||
let Ok(McpPlan::Live(live)) = mcp_plan(&args(None, false, &["in"], &["out", "more"]), &on) else { panic!("live") };
|
||||
assert_eq!(live.read_roots, [std::path::PathBuf::from("in")]);
|
||||
assert_eq!(live.write_roots, [std::path::PathBuf::from("out"), std::path::PathBuf::from("more")], "every write root is kept");
|
||||
assert!(matches!(mcp_plan(&args(None, false, &[], &[]), &on), Ok(McpPlan::Live(_))));
|
||||
}
|
||||
|
||||
fn token_folder() -> Option<std::path::PathBuf> {
|
||||
Some(std::env::temp_dir().join(format!("figcraft-cli-attach-token-{}", std::process::id())))
|
||||
}
|
||||
|
||||
// This machine's token file goes only to this machine's app, never to another host on the same
|
||||
// port.
|
||||
#[test]
|
||||
fn attach_sends_the_local_token_only_to_loopback() {
|
||||
let app = craft_control::auth::App { name: "FigCraft", data_dir: token_folder, env: |_| None, utc: |s| s.to_string(), default_port: 7979 };
|
||||
let file = app.token_path(7979).unwrap();
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "local-token\n").unwrap();
|
||||
for local in ["127.0.0.1:7979", "localhost:7979", "[::1]:7979"] {
|
||||
assert_eq!(attach_token(local, &app).as_deref(), Some("local-token"), "{local}");
|
||||
}
|
||||
for remote in ["192.168.0.2:7979", "example.com:7979", "[2001:db8::1]:7979"] {
|
||||
assert_eq!(attach_token(remote, &app), None, "{remote}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(token_folder().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_mcp_requires_both_roots_and_allowlist_cannot_carry_a_key() {
|
||||
let server = "wss://figcraft.example.com/".to_string();
|
||||
let no_roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: Vec::new() };
|
||||
assert!(matches!(mcp_roots(&no_roots, &[]), Err(CliError::Usage(_))));
|
||||
assert!(matches!(mcp_roots(&no_roots, std::slice::from_ref(&server)), Err(CliError::Usage(_))));
|
||||
|
||||
let path = std::env::temp_dir().join(format!("figcraft-cli-roots-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
let root = path.to_string_lossy().into_owned();
|
||||
let read_only = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: Vec::new() };
|
||||
assert!(matches!(mcp_roots(&read_only, &[]), Err(CliError::Usage(_))));
|
||||
let roots = RootArgs { automation_read_root: Vec::new(), automation_write_root: vec![path.to_string_lossy().into_owned()] };
|
||||
assert!(matches!(mcp_roots(&roots, &[]), Err(CliError::Usage(_))));
|
||||
|
||||
let roots = RootArgs { automation_read_root: vec![root.clone()], automation_write_root: vec![root] };
|
||||
let allowed = mcp_roots(&roots, &[server]).unwrap();
|
||||
assert_eq!(allowed.allowed_servers(), ["wss://figcraft.example.com:443/"]);
|
||||
|
||||
let with_key = "wss://figcraft.example.com/?key=secret".to_string();
|
||||
assert!(matches!(mcp_roots(&roots, &[with_key]), Err(CliError::Usage(message)) if !message.contains("secret")));
|
||||
let _ = std::fs::remove_dir_all(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! `figcraft-cli mcp` with the ArtCraft Launcher's agents switch on (#2740): each tool call goes to
|
||||
//! the open FigCraft window, found through the connection file it publishes, and otherwise to a
|
||||
//! session without a window ([`craft_control::agents::Live`] decides, before every call). The MCP
|
||||
//! client's configuration holds no port and no token, and the app may start, quit or move to
|
||||
//! another port while the client stays connected. A session without a window is confined to the
|
||||
//! folders given to the command, or, while the switch lets agents in, the agent folders
|
||||
//! (`Documents/ArtCraft/Agents/FigCraft` unless the person picked their own).
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use craft_control::agents::{self, AgentSettings, Consent, HeadlessFolders, Live, LiveConfig, Route, Window};
|
||||
use craft_control::auth;
|
||||
use figcraft_engine::file_access::{Roots, confined};
|
||||
use figcraft_mcp::{Attached, Backend, Headless};
|
||||
use serde_json::Value;
|
||||
|
||||
/// FigCraft's id in the ArtCraft Launcher's app list.
|
||||
pub const LAUNCHER_APP_ID: &str = "figcraft";
|
||||
/// The app's name in messages and its agent folder's name.
|
||||
const APP_NAME: &str = "FigCraft";
|
||||
/// The settings folder's name in the platform folder, as the app has it (`services::APP_ID`).
|
||||
const SETTINGS_ID: &str = "FigCraft";
|
||||
|
||||
/// The stable app's settings folder, resolved as the app does (`apps/figcraft/src/services.rs`):
|
||||
/// `FIGCRAFT_CONFIG_DIR`, a `portable` marker beside the executable, else `FigCraft` in the
|
||||
/// platform folder. A Nightly keeps its own profile and never accepts agents.
|
||||
pub fn settings_dir() -> Option<PathBuf> {
|
||||
use craft_settings::{Location, Portable, Rule};
|
||||
let probe = craft_settings::Probe { platform_config_dir: platform_dir(), ..Default::default() };
|
||||
let resolved = craft_settings::paths::resolve(SETTINGS_ID, &Portable::DEFAULT, &Location::Auto, &probe);
|
||||
if resolved.rule == Rule::Fallback {
|
||||
return None;
|
||||
}
|
||||
resolved.dir
|
||||
}
|
||||
|
||||
/// The platform's config folder, read from the environment as the app reads it.
|
||||
fn platform_dir() -> Option<PathBuf> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let base = std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support"));
|
||||
#[cfg(target_os = "windows")]
|
||||
let base = std::env::var_os("APPDATA").map(PathBuf::from);
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")));
|
||||
base
|
||||
}
|
||||
|
||||
/// The app's token files, as the app describes them (`apps/figcraft/src/agents.rs`), for
|
||||
/// `mcp --attach PORT`.
|
||||
pub fn control_app() -> auth::App {
|
||||
auth::App { name: APP_NAME, data_dir: settings_dir, env, utc, default_port: 7979 }
|
||||
}
|
||||
|
||||
fn env(name: &str) -> Option<OsString> {
|
||||
std::env::var_os(format!("FIGCRAFT_{name}"))
|
||||
}
|
||||
|
||||
fn utc(secs: u64) -> String {
|
||||
format!("{secs} s after 1970")
|
||||
}
|
||||
|
||||
/// Whether the launcher's switch lets agents use FigCraft now. FigCraft has no consent of its own
|
||||
/// from before the switch.
|
||||
pub fn launcher_allows() -> bool {
|
||||
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
type WindowRoute = Arc<Mutex<Attached>>;
|
||||
|
||||
/// A session without a window and the folders it is confined to.
|
||||
#[derive(Clone)]
|
||||
pub struct Session(Arc<Mutex<Headless>>, Arc<Roots>);
|
||||
|
||||
/// The folders a session without a window may use: `folders`, with the collaboration servers
|
||||
/// `servers` allowed. The shared client knows one write folder; when it is the command's first
|
||||
/// write root, the command's other write roots (`more_write`) count too. The default agent folder
|
||||
/// is made when it is missing.
|
||||
fn session(folders: &HeadlessFolders, more_write: &[PathBuf], servers: &[String], default_folder: Option<&Path>) -> Result<Session, String> {
|
||||
if let Some(default) = default_folder
|
||||
&& (folders.write.as_deref() == Some(default) || folders.read.iter().any(|f| f == default))
|
||||
{
|
||||
std::fs::create_dir_all(default).map_err(|e| format!("can't make the agent folder {}: {e}", default.display()))?;
|
||||
}
|
||||
let text = |p: &PathBuf| p.display().to_string();
|
||||
let read: Vec<String> = folders.read.iter().map(text).collect();
|
||||
let commands = folders.write.is_some() && folders.write.as_ref() == more_write.first();
|
||||
let write: Vec<String> = if commands { more_write.iter().map(text).collect() } else { folders.write.iter().map(text).collect() };
|
||||
let roots = Roots::new(&read, &write)?.with_allowed_servers(servers.to_vec());
|
||||
Ok(Session(Arc::new(Mutex::new(Headless::new())), Arc::new(roots)))
|
||||
}
|
||||
|
||||
/// What `figcraft-cli mcp` was given.
|
||||
pub struct Options {
|
||||
/// The app's settings folder, where its connection file is.
|
||||
pub config_dir: PathBuf,
|
||||
/// `--automation-read-root`.
|
||||
pub read_roots: Vec<PathBuf>,
|
||||
/// `--automation-write-root`.
|
||||
pub write_roots: Vec<PathBuf>,
|
||||
/// `--automation-allow-server`, checked.
|
||||
pub servers: Vec<String>,
|
||||
/// How long the window may take over each request.
|
||||
pub timeout: Option<std::time::Duration>,
|
||||
/// Starts the app when a call finds it closed; `None` where this install can't.
|
||||
pub launch: Option<agents::LaunchFn>,
|
||||
/// What the person allows, read before every call.
|
||||
pub consent: Box<dyn Fn() -> bool + Send + Sync>,
|
||||
}
|
||||
|
||||
/// The MCP backend that routes each call ([`Options`]).
|
||||
pub struct LiveBackend {
|
||||
live: Live<WindowRoute, Session>,
|
||||
}
|
||||
|
||||
impl LiveBackend {
|
||||
pub fn new(o: Options) -> Self {
|
||||
let Options { config_dir, read_roots, write_roots, servers, timeout, launch, consent } = o;
|
||||
let write_root = write_roots.first().cloned();
|
||||
let default_folder = agents::default_folder(APP_NAME);
|
||||
let headless_default = default_folder.clone();
|
||||
let mut cfg = LiveConfig::new(
|
||||
APP_NAME,
|
||||
config_dir,
|
||||
move |_: &Path| Consent::new(consent(), AgentSettings::default()),
|
||||
move |w: &Window| {
|
||||
let a = Attached::connect(&w.addr())
|
||||
.map_err(|e| format!("can't reach the FigCraft window at {}: {e}", w.addr()))?
|
||||
.with_token(w.token.clone());
|
||||
let a = match timeout {
|
||||
Some(t) => a.with_timeout(t).map_err(|e| format!("can't reach the FigCraft window at {}: {e}", w.addr()))?,
|
||||
None => a,
|
||||
};
|
||||
Ok(Arc::new(Mutex::new(a)))
|
||||
},
|
||||
move |folders: &HeadlessFolders| session(folders, &write_roots, &servers, headless_default.as_deref()),
|
||||
);
|
||||
cfg.read_roots = read_roots;
|
||||
cfg.write_root = write_root;
|
||||
cfg.default_folder = default_folder;
|
||||
cfg.launch = launch;
|
||||
Self { live: Live::new(cfg) }
|
||||
}
|
||||
|
||||
/// Run `window` or `headless` on the route the next call takes.
|
||||
fn route<R>(
|
||||
&self,
|
||||
window: impl FnOnce(&mut Attached) -> Result<R, String>,
|
||||
headless: impl FnOnce(&mut Headless) -> Result<R, String>,
|
||||
) -> Result<R, String> {
|
||||
match self.live.resolve()? {
|
||||
Route::Window(w) => window(&mut w.lock().unwrap_or_else(PoisonError::into_inner)),
|
||||
Route::Headless(Session(h, roots)) => confined(Some(&roots), || headless(&mut h.lock().unwrap_or_else(PoisonError::into_inner))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Backend for LiveBackend {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
let p = params.clone();
|
||||
self.route(|w| w.call(method, params), |h| h.call(method, p))
|
||||
}
|
||||
|
||||
fn has_ui(&self) -> bool {
|
||||
matches!(self.live.current(), Some(Route::Window(_)))
|
||||
}
|
||||
|
||||
fn describe(&self) -> String {
|
||||
"the open FigCraft window while the ArtCraft Launcher lets agents use it, otherwise headless".into()
|
||||
}
|
||||
|
||||
fn render_png(&mut self, ids: &[u64], scale: f64) -> Result<Vec<u8>, String> {
|
||||
self.route(|w| w.render_png(ids, scale), |h| h.render_png(ids, scale))
|
||||
}
|
||||
|
||||
fn screenshot_png(&mut self) -> Result<Vec<u8>, String> {
|
||||
self.route(Backend::screenshot_png, Backend::screenshot_png)
|
||||
}
|
||||
|
||||
fn window_png(&mut self, window: u64) -> Result<Vec<u8>, String> {
|
||||
self.route(|w| w.window_png(window), |h| h.window_png(window))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "live_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,153 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
|
||||
use craft_control::agents::Connection;
|
||||
use serde_json::json;
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-cli-live-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A FigCraft window that takes connections whose first request carries `token`, answers every
|
||||
/// request with `{"from": "window", "method": …}`, and refuses others as the app does.
|
||||
fn fake_window(token: &'static str) -> u16 {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming().flatten() {
|
||||
std::thread::spawn(move || serve(stream, token));
|
||||
}
|
||||
});
|
||||
port
|
||||
}
|
||||
|
||||
fn serve(stream: TcpStream, token: &str) {
|
||||
let mut out = stream.try_clone().unwrap();
|
||||
let mut shown = false;
|
||||
for line in BufReader::new(stream).lines().map_while(Result::ok) {
|
||||
let v: Value = serde_json::from_str(&line).unwrap();
|
||||
if !shown && v["token"].as_str() != Some(token) {
|
||||
let _ = writeln!(out, "{}", json!({"id": v["id"], "ok": false, "error": "this FigCraft control channel needs its token"}));
|
||||
return;
|
||||
}
|
||||
shown = true;
|
||||
let _ = writeln!(out, "{}", json!({"id": v["id"], "ok": true, "result": {"from": "window", "method": v["method"]}}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Publish a window on `port` in `dir` as the app does, its token file holding `token`.
|
||||
fn publish(dir: &Path, port: u16, token: &str) {
|
||||
let file = dir.join(agents::TOKEN_FILE);
|
||||
std::fs::write(&file, format!("{token}\n")).unwrap();
|
||||
// Owner-only like the app's own token file: the client refuses one others can read (Unix).
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
agents::write_connection(dir, &Connection::new(port, file, "FigCraft")).unwrap();
|
||||
}
|
||||
|
||||
fn options(dir: &Path, allowed: bool) -> Options {
|
||||
Options {
|
||||
config_dir: dir.to_path_buf(),
|
||||
read_roots: vec![dir.to_path_buf()],
|
||||
write_roots: vec![dir.to_path_buf()],
|
||||
servers: Vec::new(),
|
||||
timeout: None,
|
||||
launch: None,
|
||||
consent: Box::new(move || allowed),
|
||||
}
|
||||
}
|
||||
|
||||
// With the launcher's switch on and the app accepting agents, a call goes to the open window, with
|
||||
// the token from the app's token file.
|
||||
#[test]
|
||||
fn a_call_goes_to_the_open_window_with_its_token() {
|
||||
let dir = folder("window");
|
||||
publish(&dir, fake_window("the-token"), "the-token");
|
||||
let mut backend = LiveBackend::new(options(&dir, true));
|
||||
assert!(!backend.has_ui(), "nothing resolved yet");
|
||||
let reply = backend.call("document.inspect", json!({})).unwrap();
|
||||
assert_eq!(reply, json!({"from": "window", "method": "document.inspect"}));
|
||||
assert!(backend.has_ui());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// A token file that holds another token: the window refuses, and the call says why.
|
||||
#[test]
|
||||
fn a_window_that_refuses_the_token_fails_the_call() {
|
||||
let dir = folder("wrong-token");
|
||||
publish(&dir, fake_window("the-token"), "stale-token");
|
||||
let mut backend = LiveBackend::new(options(&dir, true));
|
||||
let error = backend.call("document.inspect", json!({})).unwrap_err();
|
||||
assert!(error.contains("needs its token"), "the window's own refusal: {error}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// The launcher's switch off: the app publishes no window (it removes its file then), and the call
|
||||
// runs headless in the folders given to the command.
|
||||
#[test]
|
||||
fn with_the_switch_off_a_call_runs_without_a_window() {
|
||||
let dir = folder("off");
|
||||
let mut backend = LiveBackend::new(options(&dir, false));
|
||||
let reply = backend.call("engine.commands", json!({})).unwrap();
|
||||
assert_ne!(reply.get("from"), Some(&json!("window")), "{reply}");
|
||||
assert!(!backend.has_ui());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// Every write root given to the command counts, not only the first the shared client knows.
|
||||
#[test]
|
||||
fn a_headless_session_keeps_every_write_root() {
|
||||
let dir = folder("roots");
|
||||
let (one, two) = (dir.join("one"), dir.join("two"));
|
||||
std::fs::create_dir_all(&one).unwrap();
|
||||
std::fs::create_dir_all(&two).unwrap();
|
||||
let mut o = options(&dir, false);
|
||||
o.write_roots = vec![one.clone(), two.clone()];
|
||||
let mut backend = LiveBackend::new(o);
|
||||
for folder in [&one, &two] {
|
||||
let path = folder.join("x.figcraft");
|
||||
backend.call("engine.execute", json!({"command": "file.saveAs", "params": {"path": path.display().to_string()}})).unwrap();
|
||||
assert!(path.exists(), "{}", path.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// A headless session is confined to its folders: a file outside them is refused.
|
||||
#[test]
|
||||
fn a_headless_session_is_confined_to_its_folders() {
|
||||
let dir = folder("confined");
|
||||
let outside = folder("confined-outside");
|
||||
let mut backend = LiveBackend::new(options(&dir, false));
|
||||
let path = outside.join("x.figcraft");
|
||||
let error = backend.call("engine.execute", json!({"command": "file.saveAs", "params": {"path": path.display().to_string()}})).unwrap_err();
|
||||
assert!(error.contains("automation path rejected"), "{error}");
|
||||
assert!(!path.exists(), "nothing written outside the folders");
|
||||
let inside = dir.join("x.figcraft");
|
||||
backend.call("engine.execute", json!({"command": "file.saveAs", "params": {"path": inside.display().to_string()}})).unwrap();
|
||||
assert!(inside.exists(), "saved inside the folders");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
|
||||
// #2740: a connection file a crashed app left behind (nothing listens on its port any more) is not
|
||||
// used: the call doesn't go there, and runs without a window in the command's folders.
|
||||
#[test]
|
||||
fn a_stale_connection_file_is_not_used() {
|
||||
let dir = folder("stale");
|
||||
let gone = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||||
publish(&dir, gone, "the-token");
|
||||
let mut backend = LiveBackend::new(options(&dir, false));
|
||||
let reply = backend.call("engine.commands", json!({})).unwrap();
|
||||
assert_ne!(reply.get("from"), Some(&json!("window")), "{reply}");
|
||||
assert!(!backend.has_ui(), "no window behind a stale file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -4,7 +4,10 @@ use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn bin() -> Command {
|
||||
Command::new(env!("CARGO_BIN_EXE_figcraft-cli"))
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_figcraft-cli"));
|
||||
// The ArtCraft Launcher's agents switch on this machine must not change what `mcp` does here.
|
||||
command.env("CRAFT_FLAGS", "-AI-MCP");
|
||||
command
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> std::path::PathBuf {
|
||||
@@ -244,7 +247,18 @@ fn run_takes_the_documented_gradient_shorthand() {
|
||||
|
||||
#[test]
|
||||
fn mcp_over_stdio() {
|
||||
let mut child = bin().arg("mcp").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap();
|
||||
let d = tmp("mcp-over-stdio");
|
||||
let mut child = bin()
|
||||
.arg("mcp")
|
||||
.arg("--automation-read-root")
|
||||
.arg(&d)
|
||||
.arg("--automation-write-root")
|
||||
.arg(&d)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
{
|
||||
let stdin = child.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}}"#).unwrap();
|
||||
@@ -261,6 +275,7 @@ fn mcp_over_stdio() {
|
||||
assert_eq!(lines[0]["result"]["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(lines[1]["error"]["code"], -32700);
|
||||
assert_eq!(lines[2]["result"]["isError"], false);
|
||||
let _ = std::fs::remove_dir_all(d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -270,8 +285,18 @@ fn mcp_over_stdio_confined_to_automation_roots() {
|
||||
std::fs::create_dir_all(d.join(sub)).unwrap();
|
||||
}
|
||||
let p = |rel: &str| d.join(rel).to_string_lossy().into_owned();
|
||||
// A root that isn't a folder stops the server before it serves.
|
||||
let out = bin().args(["mcp", "--automation-read-root", &p("missing")]).output().unwrap();
|
||||
for args in [
|
||||
vec!["mcp".to_owned()],
|
||||
vec!["mcp".to_owned(), "--automation-read-root".to_owned(), p("in")],
|
||||
vec!["mcp".to_owned(), "--automation-write-root".to_owned(), p("out")],
|
||||
] {
|
||||
let out = bin().args(args).output().unwrap();
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("requires both --automation-read-root and --automation-write-root"));
|
||||
}
|
||||
|
||||
// Both roots are required; a root that isn't a folder stops the server before it serves.
|
||||
let out = bin().args(["mcp", "--automation-read-root", &p("missing"), "--automation-write-root", &p("out")]).output().unwrap();
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("--automation-read-root"));
|
||||
let mut child = bin()
|
||||
|
||||
@@ -220,3 +220,82 @@ fn a_server_key_flag_and_an_unreachable_app_fail_with_exit_1_and_a_message() {
|
||||
assert!(got.err.contains("can't reach the FigCraft app at 127.0.0.1:1"), "{}", got.err);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// `--strict` writes what leaves nothing out as without it, and refuses (exit 1, the reasons listed,
|
||||
/// no file written or replaced) what would leave something out.
|
||||
#[test]
|
||||
fn strict_refuses_to_write_what_would_leave_content_out() {
|
||||
let dir = workdir("strict");
|
||||
let path = |name: &str| dir.join(name).to_str().unwrap().to_string();
|
||||
let frame = r#"{"command": "frame.create", "params": {"x": 0, "y": 0, "width": 10, "height": 10, "name": "F"}}"#;
|
||||
// The .fig format has no place for comments, so the writer reports one as left out.
|
||||
let comment = r#"{"command": "comment.add", "params": {"x": 5, "y": 5, "text": "Check"}}"#;
|
||||
let (clean, noted, script) = (path("clean.figcraft"), path("noted.figcraft"), path("s.json"));
|
||||
for (doc, steps) in [(&clean, format!("[{frame}]")), (¬ed, format!("[{frame}, {comment}]"))] {
|
||||
std::fs::write(&script, steps).unwrap();
|
||||
let made = invoke(["run", script.as_str(), "--out", doc.as_str()]);
|
||||
assert_eq!(made.code, 0, "{}", made.err);
|
||||
}
|
||||
|
||||
let fig = path("clean.fig");
|
||||
let got = invoke(["export", clean.as_str(), "-o", fig.as_str(), "--strict"]);
|
||||
assert_eq!((got.code, got.err.contains("note:")), (0, false), "{}", got.err);
|
||||
assert_eq!(invoke(["info", fig.as_str()]).code, 0, "the strict export reads back");
|
||||
let got = invoke(["convert", clean.as_str(), path("clean.penpot").as_str(), "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
|
||||
let (absent, previous) = (path("absent.fig"), path("previous.fig"));
|
||||
std::fs::write(&previous, b"previous export").unwrap();
|
||||
for args in [
|
||||
vec!["export", noted.as_str(), "-o", absent.as_str(), "--strict"],
|
||||
vec!["export", noted.as_str(), "-o", previous.as_str(), "--strict"],
|
||||
vec!["convert", noted.as_str(), absent.as_str(), "--strict"],
|
||||
vec!["run", script.as_str(), "--in", clean.as_str(), "--out", previous.as_str(), "--strict"],
|
||||
] {
|
||||
let got = invoke(args.iter().copied());
|
||||
assert_eq!(got.code, 1, "{args:?}: {}", got.err);
|
||||
assert!(
|
||||
got.err.starts_with("error: ") && got.err.contains("--strict") && got.err.contains("comments were left out"),
|
||||
"{args:?}: {}",
|
||||
got.err
|
||||
);
|
||||
assert!(!std::path::Path::new(&absent).exists(), "{args:?} wrote {absent}");
|
||||
assert_eq!(std::fs::read(&previous).unwrap(), b"previous export", "{args:?} replaced {previous}");
|
||||
}
|
||||
// Without --strict the same export writes the file and notes what it left out.
|
||||
let got = invoke(["export", noted.as_str(), "-o", absent.as_str()]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(got.err.contains("note: comments were left out") && std::path::Path::new(&absent).exists(), "{}", got.err);
|
||||
|
||||
// A folder of drawables is written only when no file in it leaves anything out.
|
||||
let drawables = path("clean-drawables");
|
||||
let got = invoke(["export", clean.as_str(), "-o", drawables.as_str(), "--format", "xml", "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
assert!(std::path::Path::new(&drawables).join("F.xml").exists(), "{}", got.out);
|
||||
std::fs::write(
|
||||
&script,
|
||||
r##"[{"command": "shape.rectangle", "params": {"x": 0, "y": 0, "width": 24, "height": 24, "name": "Dot", "props": {"fill": "#ff0000", "effects": [{"type": "dropShadow"}]}}}]"##,
|
||||
)
|
||||
.unwrap();
|
||||
let shadowed = path("shadowed.figcraft");
|
||||
assert_eq!(invoke(["run", script.as_str(), "--out", shadowed.as_str()]).code, 0);
|
||||
let folder = path("drawables");
|
||||
let got = invoke(["export", shadowed.as_str(), "-o", folder.as_str(), "--format", "xml", "--strict"]);
|
||||
assert_eq!(got.code, 1, "{}", got.err);
|
||||
assert!(got.err.contains("drop shadows were left out") && !std::path::Path::new(&folder).exists(), "{}", got.err);
|
||||
|
||||
// --vd-compat only matters for drawables.
|
||||
let got = invoke(["export", clean.as_str(), "-o", path("ignored.fig").as_str(), "--vd-compat", "ignore", "--strict"]);
|
||||
assert_eq!(got.code, 0, "{}", got.err);
|
||||
// Where nothing would be checked, --strict is a usage error.
|
||||
for args in [
|
||||
vec!["export", clean.as_str(), "-o", "x.png", "--strict"],
|
||||
vec!["export", clean.as_str(), "-o", "frames", "--strict"],
|
||||
vec!["export", shadowed.as_str(), "-o", "x.xml", "--vd-compat", "ignore", "--strict"],
|
||||
vec!["convert", clean.as_str(), "x.svg", "--strict"],
|
||||
vec!["run", script.as_str(), "--strict"],
|
||||
] {
|
||||
assert!(usage_error(&args).contains("--strict"), "{args:?}");
|
||||
}
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
//! Crash and compaction simulation over many seeds, on the real data directory: several clients
|
||||
//! edit (and undo) one file while the store logs, flushes and compacts it, connections drop, and
|
||||
//! the server crashes (the [`Store`] and session dropped with nothing more written) before a
|
||||
//! flush, in the middle of one (its records cut short on disk) or after one but before anyone
|
||||
//! heard back. Everyone leaving compacts and parks the file. As the hub does, nobody hears of a
|
||||
//! change before its flush.
|
||||
//!
|
||||
//! After every restart the file must come back as exactly the state the server had at some
|
||||
//! sequence number, no earlier than the last durable point (a clean flush or a compaction) and
|
||||
//! no earlier than anything a client heard; valid; and taking appends again. Clients resume with
|
||||
//! their ids, resend what the server lost, and end with exactly its state.
|
||||
//!
|
||||
//! One seed: `FIGCRAFT_DST_SEED=7 cargo test -p figcraft-server dst_crash`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use figcraft_collab::message::{Access, ClientMsg, ServerMsg};
|
||||
use figcraft_collab::sim::Rng;
|
||||
use figcraft_collab::{Client, NoRecompute, Notice, Outgoing, Replica, Server};
|
||||
use figcraft_collab_net::hub::Backend;
|
||||
use figcraft_doc::{Document, NodeId, NodeKind, Style, StyleKind};
|
||||
|
||||
use crate::disk::{self, LOG};
|
||||
use crate::store::{FILES, Store, StoreConfig};
|
||||
use crate::test_util::{TempDir, config};
|
||||
|
||||
const CLIENTS: usize = 3;
|
||||
|
||||
fn fixture() -> Document {
|
||||
let mut d = Document::new("Crash DST");
|
||||
let page = d.first_page().unwrap();
|
||||
for i in 0..3 {
|
||||
let f = d.create(page, NodeKind::Frame, &format!("F{i}"), i as f64 * 200.0, 0.0, 150.0, 100.0).unwrap();
|
||||
for j in 0..2 {
|
||||
d.create(f, NodeKind::Rectangle, &format!("R{i}{j}"), 0.0, j as f64 * 20.0, 10.0, 10.0).unwrap();
|
||||
}
|
||||
}
|
||||
d.repair();
|
||||
d.take_dirty();
|
||||
d
|
||||
}
|
||||
|
||||
/// One random edit: layers created, moved, resized, renamed, deleted; pages and styles.
|
||||
fn random_edit(doc: &mut Document, rng: &mut Rng) {
|
||||
let layers: Vec<NodeId> = doc.nodes().filter(|n| !n.is_page()).map(|n| n.id).collect();
|
||||
let containers: Vec<NodeId> = doc.nodes().filter(|n| n.kind.is_container()).map(|n| n.id).collect();
|
||||
match rng.below(9) {
|
||||
0 | 1 => {
|
||||
if let Some(&p) = rng.pick(&containers) {
|
||||
let _ = doc.create(p, NodeKind::Rectangle, "New", rng.below(300) as f64, rng.below(300) as f64, 8.0, 8.0);
|
||||
}
|
||||
}
|
||||
2 | 3 => {
|
||||
if let Some(n) = rng.pick(&layers).copied().and_then(|x| doc.node_mut(x)) {
|
||||
n.width = 1.0 + rng.below(400) as f64;
|
||||
n.opacity = rng.below(11) as f32 / 10.0;
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
if let Some(n) = rng.pick(&layers).copied().and_then(|x| doc.node_mut(x)) {
|
||||
n.name = format!("Layer {}", rng.below(1000));
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
if let Some(&x) = rng.pick(&layers).filter(|_| rng.chance(0.5)) {
|
||||
let _ = doc.remove(x);
|
||||
}
|
||||
}
|
||||
6 => {
|
||||
if let (Some(&x), Some(&p)) = (rng.pick(&layers), rng.pick(&containers)) {
|
||||
let _ = doc.place(x, p, 0);
|
||||
}
|
||||
}
|
||||
7 => {
|
||||
let pages = doc.pages.clone();
|
||||
match rng.pick(&pages).copied().and_then(|p| doc.node_mut(p)) {
|
||||
Some(n) if rng.chance(0.7) => n.name = format!("Page {}", rng.below(100)),
|
||||
_ => {
|
||||
doc.add_page("More");
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let id = doc.new_style_id();
|
||||
let name = format!("Style {}", rng.below(100));
|
||||
doc.styles.push(Style { id, name, description: String::new(), kind: StyleKind::Paint { paints: vec![] }, bound: Default::default() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hello(i: usize) -> figcraft_collab::Hello {
|
||||
let ClientMsg::Hello(h) = Client::hello("f", "", &format!("Person {i}"), "#3366FF") else { panic!("not a hello") };
|
||||
h
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Crash {
|
||||
/// Before the pending records were written.
|
||||
BeforeFlush,
|
||||
/// While they were written: the log ends inside them.
|
||||
Torn,
|
||||
/// After a clean flush, before anyone heard back.
|
||||
BeforeAcks,
|
||||
}
|
||||
|
||||
/// One file in a data directory, its live session and its clients.
|
||||
struct Rig {
|
||||
seed: u64,
|
||||
rng: Rng,
|
||||
dir: TempDir,
|
||||
cfg: StoreConfig,
|
||||
store: Option<Store>,
|
||||
server: Server,
|
||||
file: String,
|
||||
clients: Vec<Client>,
|
||||
online: Vec<bool>,
|
||||
/// What the server sent, to deliver once it is flushed: (client index, message).
|
||||
outbox: Vec<(usize, ServerMsg)>,
|
||||
/// The server's state after each sequence number, on the timeline that survived.
|
||||
history: BTreeMap<u64, Replica>,
|
||||
/// The last state on disk for sure (a clean flush or a compaction).
|
||||
durable: (u64, Replica),
|
||||
compactions: u64,
|
||||
/// Compactions over every store opened.
|
||||
compacted: u64,
|
||||
crashes: Vec<Crash>,
|
||||
/// Torn crashes whose log ended inside a record (reported at the next open).
|
||||
damaged: usize,
|
||||
idles: usize,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(seed: u64) -> Rig {
|
||||
let dir = TempDir::new(&format!("dst-crash-{seed}"));
|
||||
let cfg = StoreConfig { compact_after: 3 + (seed % 6) as usize, ..config(dir.path()).store() };
|
||||
let mut store = Store::open(dir.path(), cfg.clone()).unwrap();
|
||||
let (info, _, _) = store.publish("DST", &Replica::new(fixture()).snapshot().unwrap()).unwrap();
|
||||
let mut server = store.open(&info.id).unwrap();
|
||||
let start = server.replica().clone();
|
||||
let mut clients = Vec::new();
|
||||
let mut outs = Vec::new();
|
||||
for i in 0..CLIENTS {
|
||||
let (id, out) = server.join_as(hello(i), Access::Edit).unwrap();
|
||||
store.changed(&info.id, &mut server);
|
||||
assert!(store.flush().is_empty());
|
||||
let mut welcome = None;
|
||||
for o in out {
|
||||
match o {
|
||||
Outgoing::To(to, m @ ServerMsg::Welcome { .. }) if to == id => welcome = Some(m),
|
||||
o => outs.push(o),
|
||||
}
|
||||
}
|
||||
clients.push(Client::join(welcome.unwrap()).unwrap());
|
||||
}
|
||||
let compactions = store.compactions();
|
||||
let mut rig = Rig {
|
||||
seed,
|
||||
rng: Rng::new(seed ^ 0xD57),
|
||||
dir,
|
||||
cfg,
|
||||
store: Some(store),
|
||||
server,
|
||||
file: info.id,
|
||||
clients,
|
||||
online: vec![true; CLIENTS],
|
||||
outbox: Vec::new(),
|
||||
history: BTreeMap::from([(0, start.clone())]),
|
||||
durable: (0, start),
|
||||
compactions,
|
||||
compacted: 0,
|
||||
crashes: Vec::new(),
|
||||
damaged: 0,
|
||||
idles: 0,
|
||||
};
|
||||
rig.route(outs);
|
||||
rig.deliver();
|
||||
rig
|
||||
}
|
||||
|
||||
fn store(&mut self) -> &mut Store {
|
||||
self.store.as_mut().unwrap()
|
||||
}
|
||||
|
||||
fn log_path(&self) -> PathBuf {
|
||||
self.dir.path().join(FILES).join(&self.file).join(LOG)
|
||||
}
|
||||
|
||||
fn log_len(&self) -> u64 {
|
||||
fs::metadata(self.log_path()).map_or(0, |m| m.len())
|
||||
}
|
||||
|
||||
/// Queue what the server sent for the clients connected now.
|
||||
fn route(&mut self, out: Vec<Outgoing>) {
|
||||
for o in out {
|
||||
let ids: Vec<u32> = self.clients.iter().map(Client::id).collect();
|
||||
let (msg, targets): (ServerMsg, Vec<usize>) = match o {
|
||||
Outgoing::To(id, m) => (m, ids.iter().position(|c| *c == id).into_iter().collect()),
|
||||
Outgoing::All(m) => (m, (0..CLIENTS).collect()),
|
||||
Outgoing::Others(id, m) => (m, (0..CLIENTS).filter(|i| ids[*i] != id).collect()),
|
||||
};
|
||||
for t in targets.into_iter().filter(|t| self.online[*t]) {
|
||||
self.outbox.push((t, msg.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The store logs what the server just did (and may compact); the timeline grows.
|
||||
fn logged(&mut self, out: Vec<Outgoing>) {
|
||||
let file = self.file.clone();
|
||||
let store = self.store.as_mut().unwrap();
|
||||
store.changed(&file, &mut self.server);
|
||||
let compactions = store.compactions();
|
||||
let seq = self.server.seq();
|
||||
self.history.entry(seq).or_insert_with(|| self.server.replica().clone());
|
||||
if compactions != self.compactions {
|
||||
self.compacted += compactions - self.compactions;
|
||||
self.compactions = compactions;
|
||||
self.durable = (seq, self.server.replica().clone());
|
||||
}
|
||||
self.route(out);
|
||||
}
|
||||
|
||||
fn send(&mut self, i: usize, msg: ClientMsg) {
|
||||
let id = self.clients[i].id();
|
||||
let out = self.server.receive(id, msg);
|
||||
self.logged(out);
|
||||
}
|
||||
|
||||
/// A clean flush: what is logged is durable.
|
||||
fn flush(&mut self) {
|
||||
let file = self.file.clone();
|
||||
let failed = self.store().flush();
|
||||
assert!(!failed.contains(&file), "seed {}: the log couldn't be written", self.seed);
|
||||
self.durable = (self.server.seq(), self.server.replica().clone());
|
||||
}
|
||||
|
||||
/// Flush, then let the clients hear everything, until nothing more is said.
|
||||
fn deliver(&mut self) {
|
||||
for _ in 0..10_000 {
|
||||
if self.outbox.is_empty() {
|
||||
return;
|
||||
}
|
||||
self.flush();
|
||||
for (i, msg) in std::mem::take(&mut self.outbox) {
|
||||
if !self.online[i] {
|
||||
continue;
|
||||
}
|
||||
let replies = self.clients[i].receive(msg, &NoRecompute).unwrap();
|
||||
for r in replies {
|
||||
self.send(i, r);
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("seed {}: the session never went quiet", self.seed);
|
||||
}
|
||||
|
||||
fn edit(&mut self, i: usize) {
|
||||
let mut doc = self.clients[i].document().clone();
|
||||
let mut rng = Rng::new(self.rng.next_u64());
|
||||
random_edit(&mut doc, &mut rng);
|
||||
// Offline (or before the welcome) it is queued.
|
||||
if let Some(m) = self.clients[i].edit(&doc).unwrap() {
|
||||
self.send(i, m);
|
||||
}
|
||||
}
|
||||
|
||||
fn undo(&mut self, i: usize) {
|
||||
let msgs = if self.rng.chance(0.6) { self.clients[i].undo(&NoRecompute) } else { self.clients[i].redo(&NoRecompute) };
|
||||
for m in msgs.unwrap() {
|
||||
self.send(i, m);
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection drops: what was on its way to the client is lost.
|
||||
fn disconnect(&mut self, i: usize) {
|
||||
if !self.online[i] {
|
||||
return;
|
||||
}
|
||||
self.online[i] = false;
|
||||
self.outbox.retain(|(t, _)| *t != i);
|
||||
self.clients[i].disconnect();
|
||||
let out = self.server.leave(self.clients[i].id());
|
||||
self.logged(out);
|
||||
}
|
||||
|
||||
fn reconnect(&mut self, i: usize) {
|
||||
if self.online[i] {
|
||||
return;
|
||||
}
|
||||
let ClientMsg::Hello(h) = self.clients[i].reconnect(hello(i)) else { panic!("not a hello") };
|
||||
let (id, out) = self.server.join_as(h, Access::Edit).unwrap();
|
||||
assert_eq!(id, self.clients[i].id(), "seed {}: client {i} came back as someone else", self.seed);
|
||||
self.online[i] = true;
|
||||
self.logged(out);
|
||||
}
|
||||
|
||||
/// The server dies; the clients' connections with it. Then it starts again from the disk.
|
||||
fn crash(&mut self, mut how: Crash) {
|
||||
let seed = self.seed;
|
||||
let mut torn_at = None;
|
||||
match how {
|
||||
Crash::BeforeFlush => {}
|
||||
Crash::BeforeAcks => self.flush(),
|
||||
Crash::Torn => {
|
||||
let before = self.log_len();
|
||||
let file = self.file.clone();
|
||||
assert!(!self.store().flush().contains(&file));
|
||||
let after = self.log_len();
|
||||
if after > before {
|
||||
// Cut inside the new records: a cut on a record boundary is moved on to the
|
||||
// next byte that isn't one.
|
||||
let bytes = fs::read(self.log_path()).unwrap();
|
||||
let mut at = before + self.rng.below((after - before) as usize) as u64;
|
||||
while at + 1 < after && disk::read_log(&bytes[..at as usize]).unwrap().damaged.is_none() {
|
||||
at += 1;
|
||||
}
|
||||
torn_at = Some(at);
|
||||
} else {
|
||||
// Nothing was pending: that was a clean flush.
|
||||
self.durable = (self.server.seq(), self.server.replica().clone());
|
||||
how = Crash::BeforeAcks;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nothing more is written: no flush, no compaction, no goodbye.
|
||||
drop(self.store.take());
|
||||
self.outbox.clear();
|
||||
for i in 0..CLIENTS {
|
||||
self.online[i] = false;
|
||||
self.clients[i].disconnect();
|
||||
}
|
||||
let mut damaged = false;
|
||||
if let Some(at) = torn_at {
|
||||
let bytes = fs::read(self.log_path()).unwrap();
|
||||
let cut = &bytes[..at as usize];
|
||||
damaged = disk::read_log(cut).unwrap().damaged.is_some();
|
||||
fs::write(self.log_path(), cut).unwrap();
|
||||
}
|
||||
self.crashes.push(how);
|
||||
self.damaged += usize::from(damaged);
|
||||
|
||||
let mut store = Store::open(self.dir.path(), self.cfg.clone()).unwrap();
|
||||
self.server = store.open(&self.file).unwrap();
|
||||
let seq = self.server.seq();
|
||||
let what = format!("seed {seed}: after a crash {how:?} (durable {}, reopened {seq})", self.durable.0);
|
||||
if damaged {
|
||||
assert!(store.problems().iter().any(|p| p.contains(&self.file)), "{what}: the cut-short log wasn't reported");
|
||||
}
|
||||
if how == Crash::Torn {
|
||||
assert!(seq >= self.durable.0, "{what}: lost flushed edits");
|
||||
} else {
|
||||
assert_eq!(seq, self.durable.0, "{what}");
|
||||
assert!(self.server.replica() == &self.durable.1, "{what}: not the state on disk");
|
||||
}
|
||||
let Some(expected) = self.history.get(&seq) else { panic!("{what}: a sequence number the server never had") };
|
||||
assert!(self.server.replica() == expected, "{what}: not the state the server had then");
|
||||
assert!(self.server.document().validate().is_empty(), "{what}: {:?}", self.server.document().validate());
|
||||
// Nobody heard of anything that didn't survive, and what they heard is what came back.
|
||||
for (i, c) in self.clients.iter().enumerate() {
|
||||
assert!(c.seq() <= seq, "{what}: client {i} heard of seq {}", c.seq());
|
||||
assert!(c.confirmed() == &self.history[&c.seq()], "{what}: client {i}'s confirmed state isn't the server's at {}", c.seq());
|
||||
}
|
||||
// What came after the surviving sequence number is gone: new batches take those numbers.
|
||||
self.history.retain(|s, _| *s <= seq);
|
||||
self.durable = (seq, self.server.replica().clone());
|
||||
self.compactions = store.compactions();
|
||||
self.store = Some(store);
|
||||
for i in 0..CLIENTS {
|
||||
if self.rng.chance(0.8) {
|
||||
self.reconnect(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everyone leaves: the file is compacted and parked, and opened again on the next join.
|
||||
fn everyone_leaves(&mut self) {
|
||||
for i in 0..CLIENTS {
|
||||
self.disconnect(i);
|
||||
}
|
||||
self.deliver();
|
||||
self.flush();
|
||||
let before = self.server.replica().clone();
|
||||
let file = self.file.clone();
|
||||
let mut server = std::mem::replace(&mut self.server, Server::new(Document::new(""), "", self.cfg.core));
|
||||
let store = self.store.as_mut().unwrap();
|
||||
store.idle(&file, &mut server);
|
||||
self.server = store.open(&file).unwrap();
|
||||
self.compacted += store.compactions() - self.compactions;
|
||||
self.compactions = store.compactions();
|
||||
assert!(self.server.replica() == &before, "seed {}: the file came back changed after everyone left", self.seed);
|
||||
self.durable = (self.server.seq(), before);
|
||||
self.idles += 1;
|
||||
for i in 0..CLIENTS {
|
||||
self.reconnect(i);
|
||||
}
|
||||
}
|
||||
|
||||
/// Everyone back and up to date, then edits until the server holds batches not yet flushed.
|
||||
fn pending_edits(&mut self) {
|
||||
for i in 0..CLIENTS {
|
||||
self.reconnect(i);
|
||||
}
|
||||
self.deliver();
|
||||
for _ in 0..1_000 {
|
||||
if self.server.seq() > self.durable.0 {
|
||||
return;
|
||||
}
|
||||
let i = self.rng.below(CLIENTS);
|
||||
self.edit(i);
|
||||
}
|
||||
panic!("seed {}: no edit was accepted", self.seed);
|
||||
}
|
||||
|
||||
fn step(&mut self) {
|
||||
let i = self.rng.below(CLIENTS);
|
||||
match self.rng.below(24) {
|
||||
0..=8 => self.edit(i),
|
||||
9 | 10 => {
|
||||
if self.online[i] {
|
||||
self.undo(i);
|
||||
}
|
||||
}
|
||||
11..=13 => self.deliver(),
|
||||
14 | 15 => self.disconnect(i),
|
||||
16 | 17 => self.reconnect(i),
|
||||
18 => {
|
||||
let how = [Crash::BeforeFlush, Crash::Torn, Crash::BeforeAcks][self.rng.below(3)];
|
||||
self.crash(how);
|
||||
}
|
||||
19 => self.everyone_leaves(),
|
||||
_ => self.edit(i),
|
||||
}
|
||||
}
|
||||
|
||||
/// Everyone back, everything said: each client holds exactly the server's state.
|
||||
fn settle(&mut self, when: &str) {
|
||||
for i in 0..CLIENTS {
|
||||
self.reconnect(i);
|
||||
}
|
||||
self.deliver();
|
||||
let seed = self.seed;
|
||||
let server = self.server.replica();
|
||||
for (i, c) in self.clients.iter_mut().enumerate() {
|
||||
assert_eq!((c.pending(), c.seq()), (0, self.server.seq()), "seed {seed} {when}: client {i}");
|
||||
assert!(c.view() == server && c.confirmed() == server, "seed {seed} {when}: client {i} differs from the server");
|
||||
let lost: Vec<Notice> = c.take_notices().into_iter().filter(|n| matches!(n, Notice::Lost { .. })).collect();
|
||||
assert!(lost.is_empty(), "seed {seed} {when}: client {i} lost its queue: {lost:?}");
|
||||
}
|
||||
assert!(self.server.document().validate().is_empty(), "seed {seed} {when}");
|
||||
}
|
||||
}
|
||||
|
||||
fn run_seed(seed: u64) -> Rig {
|
||||
let mut rig = Rig::new(seed);
|
||||
for round in 0..3 {
|
||||
for _ in 0..25 {
|
||||
rig.step();
|
||||
}
|
||||
// Every round tears a flush of batches nobody heard of yet.
|
||||
rig.pending_edits();
|
||||
rig.crash(Crash::Torn);
|
||||
rig.settle(&format!("round {round}"));
|
||||
}
|
||||
// Everyone leaves (compacted, parked), then a crash: the compacted file is read from disk.
|
||||
rig.everyone_leaves();
|
||||
rig.crash(Crash::BeforeFlush);
|
||||
rig.settle("after a crash once everyone left");
|
||||
// Accepted and flushed, nobody heard: the clients' resends are recognised as done.
|
||||
rig.pending_edits();
|
||||
rig.crash(Crash::BeforeAcks);
|
||||
rig.settle("after a crash before the acks");
|
||||
// The last word: a crash right after everyone agreed loses nothing.
|
||||
rig.crash(Crash::BeforeFlush);
|
||||
rig.settle("after the last crash");
|
||||
assert!(rig.damaged > 0, "seed {seed}: no torn log ended inside a record");
|
||||
assert!(rig.crashes.contains(&Crash::Torn), "seed {seed}: no flush was torn");
|
||||
rig
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_crashes_compactions_and_torn_logs_lose_nothing_acknowledged() {
|
||||
let seeds: Vec<u64> = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse().ok()) {
|
||||
Some(one) => vec![one],
|
||||
None => (0..24).collect(),
|
||||
};
|
||||
// Seeds are independent (a data directory each) and mostly wait on the disk: run them side
|
||||
// by side. Each stays deterministic.
|
||||
let rigs: Vec<Rig> = std::thread::scope(|s| {
|
||||
let runs: Vec<_> = seeds.into_iter().map(|seed| s.spawn(move || run_seed(seed))).collect();
|
||||
runs.into_iter().map(|r| r.join().unwrap()).collect()
|
||||
});
|
||||
let (mut kinds, mut damaged, mut idles, mut compactions) = ([0usize; 3], 0, 0, 0);
|
||||
for rig in &rigs {
|
||||
for c in &rig.crashes {
|
||||
kinds[*c as usize] += 1;
|
||||
}
|
||||
damaged += rig.damaged;
|
||||
idles += rig.idles;
|
||||
compactions += rig.compacted;
|
||||
}
|
||||
assert!(kinds.iter().all(|k| *k > 0), "every kind of crash happens: {kinds:?}");
|
||||
assert!(damaged > 0, "some torn log ends inside a record");
|
||||
assert!(idles > 0 && compactions > 0, "files are compacted ({compactions}) and parked ({idles})");
|
||||
}
|
||||
@@ -47,7 +47,7 @@ pub(crate) fn archive(bomb: usize, padding: usize) -> Vec<u8> {
|
||||
let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
for i in 0..src.len() {
|
||||
let f = src.by_index_raw(i).unwrap();
|
||||
if bomb > 0 && f.name() == "library/document.json" {
|
||||
if bomb > 0 && f.name().expect("ZIP member name") == "library/document.json" {
|
||||
continue;
|
||||
}
|
||||
out.raw_copy_file(f).unwrap();
|
||||
|
||||
@@ -101,6 +101,8 @@ mod directory_tests;
|
||||
#[cfg(test)]
|
||||
mod download_burst_tests;
|
||||
#[cfg(test)]
|
||||
mod dst_crash_tests;
|
||||
#[cfg(test)]
|
||||
mod hardening_tests;
|
||||
#[cfg(test)]
|
||||
mod idle_io_tests;
|
||||
|
||||
@@ -90,7 +90,7 @@ impl Store {
|
||||
if let Some(why) = self.low_disk() {
|
||||
return Err(why);
|
||||
}
|
||||
let replica = Replica::from_snapshot(snapshot).map_err(|e| format!("the file couldn't be read: {e}"))?;
|
||||
let replica = Replica::from_snapshot(snapshot.to_vec()).map_err(|e| format!("the file couldn't be read: {e}"))?;
|
||||
if replica.document().node_count() > self.cfg.core.max_nodes {
|
||||
return Err(format!("the file has more than {} layers", self.cfg.core.max_nodes));
|
||||
}
|
||||
|
||||
@@ -21,8 +21,8 @@ figcraft-collab-net = { workspace = true }
|
||||
figcraft-text = { workspace = true }
|
||||
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
|
||||
# The page command API (storytold/craft-libs#413): the request plumbing behind window.figcraft.
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
|
||||
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", version = "0.1.0" }
|
||||
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "9949e08d6f29b6c4462f14af1d5007acac163dbf", version = "0.1.0" }
|
||||
base64 = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
@@ -124,7 +124,8 @@ fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
|
||||
n.get()
|
||||
});
|
||||
let gate = RequestGate::new();
|
||||
QUEUE.with(|q| q.borrow_mut().push(ControlRequest { id: json!(id), method: method.to_string(), params, reply, state: gate.clone() }));
|
||||
QUEUE
|
||||
.with(|q| q.borrow_mut().push(ControlRequest { roots: None, id: json!(id), method: method.to_string(), params, reply, state: gate.clone() }));
|
||||
CTX.with(|c| {
|
||||
if let Some(ctx) = c.borrow().as_ref() {
|
||||
ctx.request_repaint();
|
||||
|
||||
+136
-33
@@ -24,6 +24,17 @@
|
||||
//! - Everything else is a copy or export that never becomes the document: `false` — rendered
|
||||
//! images, SVG and PDF, `.fig` copies, and the variables exports (a `.variables.json`
|
||||
//! sidecar's `.json` extension doesn't make it a document).
|
||||
//! - Confirmed saves, opt-in: with `?save=managed` in the URL, or `data-save="managed"` on the
|
||||
//! canvas ([`crate::query::confirms_saves`]), each Save and Save As of the document carries an
|
||||
//! `id` (`save-1`, `save-2`, …) and the document keeps its unsaved changes until the host answers
|
||||
//! `figcraft:saved` with that `id` ([`crate::host_saves`]). Then it is saved as of the file the
|
||||
//! host stored, so edits made meanwhile stay unsaved, and a Save As becomes the document's file
|
||||
//! only then. Answers for any other `id` are ignored; a newer save replaces the one waiting; a
|
||||
//! file the host opens forgets it (the user is told). Without an answer within 30 seconds the save counts as not
|
||||
//! stored: the user is told and the host gets `figcraft:failed` with the `id`. Copies and exports
|
||||
//! carry no `id` and `saveAs: false`. A host that doesn't opt in sees no change: every file
|
||||
//! counts as saved once it is posted. `craft-web-host` has no message yet for a host to refuse a
|
||||
//! save, so a refusal shows as the timeout.
|
||||
//! - `figcraft:dirty` whenever unsaved changes appear or go away, `figcraft:failed` when the app
|
||||
//! couldn't start.
|
||||
//!
|
||||
@@ -31,10 +42,14 @@
|
||||
//! edit; `?author=` names the user for comments and board notes.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_web_host::web::{FileData, Host, Message};
|
||||
use figcraft_ui_egui::FigApp;
|
||||
use figcraft_engine::cmd::file::FileSnapshot;
|
||||
use figcraft_ui_egui::{Delivery, FigApp};
|
||||
|
||||
use crate::host_saves::HostSaves;
|
||||
|
||||
/// The app id in the host messages (`figcraft:ready`).
|
||||
const APP: &str = "figcraft";
|
||||
@@ -42,38 +57,87 @@ const APP: &str = "figcraft";
|
||||
/// The longest user name taken from `?author=`.
|
||||
const MAX_AUTHOR_CHARS: usize = 200;
|
||||
|
||||
/// Files the host sent, on their way to the app's own open queue ([`figcraft_ui_egui::pending_open`]):
|
||||
/// `(name, bytes)`.
|
||||
pub type OpenQueue = Rc<RefCell<Vec<(String, Vec<u8>)>>>;
|
||||
/// What the host sent, in the order it came, for the shell's next frame ([`Bridge::frame`]).
|
||||
enum FromHost {
|
||||
/// A file to open: `(name, bytes)`.
|
||||
Open(String, Vec<u8>),
|
||||
/// The save with this `id` is stored.
|
||||
Saved(String),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Bridge {
|
||||
host: Rc<Host>,
|
||||
/// The file the host opened, and after a `saveAs` hand-over the document's file: the name a
|
||||
/// Save under (`saveAs: false`) is decided against.
|
||||
host_file: Rc<RefCell<Option<String>>>,
|
||||
/// The host confirms saves (`?save=managed`): document saves wait for its `saved`.
|
||||
confirms_saves: bool,
|
||||
/// The document's file and the save waiting for the host ([`crate::host_saves`]).
|
||||
saves: Rc<RefCell<HostSaves<FileSnapshot>>>,
|
||||
/// Messages heard and not yet handled. The listener only queues them: a page host can answer
|
||||
/// while a post is still running, so nothing else is borrowed there.
|
||||
inbox: Rc<RefCell<VecDeque<FromHost>>>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
/// The bridge for this page, or `None` when FigCraft isn't hosted: no `?host=parent` and no
|
||||
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
|
||||
/// with downloads), or a parent on another origin.
|
||||
pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), host_file: Rc::default() })
|
||||
/// with downloads), or a parent on another origin. `confirms_saves`: the host opted in to
|
||||
/// confirmed saves.
|
||||
pub fn connect(canvas: &web_sys::HtmlCanvasElement, confirms_saves: bool) -> Option<Self> {
|
||||
Some(Self { host: Rc::new(Host::connect(APP, canvas)?), confirms_saves, saves: Rc::default(), inbox: Rc::default() })
|
||||
}
|
||||
|
||||
/// Hear the files the host sends, and queue each one on `opens` for the app's own open path
|
||||
/// (the shell drains it into [`figcraft_ui_egui::pending_open`] every frame, so a host file
|
||||
/// opens like a dropped one).
|
||||
pub fn listen(&self, opens: OpenQueue, ctx: egui::Context) {
|
||||
let host_file = self.host_file.clone();
|
||||
/// Hear the host's messages. They are handled in the shell's next frame ([`Bridge::frame`]),
|
||||
/// in the order they came.
|
||||
pub fn listen(&self, ctx: egui::Context) {
|
||||
let inbox = self.inbox.clone();
|
||||
self.host.listen(move |message| {
|
||||
if let Message::Open { name, data } = message {
|
||||
deliver_open(&opens, &ctx, &host_file, &name, &data);
|
||||
let heard = match message {
|
||||
Message::Open { name, data } => open_bytes(&name, &data),
|
||||
Message::Saved { id } => Some(FromHost::Saved(id)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(heard) = heard {
|
||||
inbox.borrow_mut().push_back(heard);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Every frame: handle what the host sent, in order (a file opens on the app's own open path,
|
||||
/// as a dropped one does; a `saved` marks its document saved), and end a save that waited too
|
||||
/// long. `now_ms`: the app's clock, which also wakes the app when the waiting save times out.
|
||||
pub fn frame(&self, fig: &mut FigApp, ctx: &egui::Context, now_ms: u64) {
|
||||
let heard = std::mem::take(&mut *self.inbox.borrow_mut());
|
||||
for message in heard {
|
||||
match message {
|
||||
FromHost::Open(name, bytes) => {
|
||||
let forgotten = self.saves.borrow_mut().opened(&name);
|
||||
if let Some(save) = forgotten {
|
||||
fig.document_not_stored(&save.name, &figcraft_ui_egui::save_forgotten_on_open());
|
||||
}
|
||||
queue_open(fig, name, bytes);
|
||||
}
|
||||
FromHost::Saved(id) => {
|
||||
let confirmed = self.saves.borrow_mut().saved(&id);
|
||||
match confirmed {
|
||||
Some(save) => fig.document_stored(&save.name, save.file),
|
||||
None => log::info!("host confirmed save {id:?}, which isn't the one waiting; ignored"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let expired = self.saves.borrow_mut().expire(now_ms);
|
||||
if let Some(save) = expired {
|
||||
let secs = self.saves.borrow().timeout_ms() / 1000;
|
||||
let _ = self.host.post_failed(&format!("save {} was not confirmed within {secs} seconds", save.id), Some(&save.id));
|
||||
fig.document_not_stored(&save.name, &figcraft_ui_egui::save_unconfirmed(usize::try_from(secs).unwrap_or(usize::MAX)));
|
||||
}
|
||||
let wait = self.saves.borrow().wait_ms(now_ms);
|
||||
if let Some(wait) = wait {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(wait));
|
||||
}
|
||||
}
|
||||
|
||||
/// `?author=`: the host's name for the user signs comments and board notes.
|
||||
pub fn set_author(app: &mut FigApp, author: &str) {
|
||||
let author: String = author.trim().chars().take(MAX_AUTHOR_CHARS).collect();
|
||||
@@ -93,24 +157,53 @@ impl Bridge {
|
||||
|
||||
/// The document file the host opened or the last Save As made, if any.
|
||||
pub fn host_file(&self) -> Option<String> {
|
||||
self.host_file.borrow().clone()
|
||||
self.saves.borrow().host_file().map(str::to_string)
|
||||
}
|
||||
|
||||
/// Hand a file the app would otherwise download to the host; `false` when nothing was
|
||||
/// delivered. The `saveAs` rule is this module's documentation's.
|
||||
/// Hand a file the app would otherwise download to the host, without an `id`; `false` when
|
||||
/// nothing was delivered. To a host that confirms saves only copies and exports come this way
|
||||
/// (the document's own file goes through [`post_document`](Self::post_document)), so they are
|
||||
/// `saveAs: false`; to one that doesn't, the `saveAs` rule is this module's documentation's.
|
||||
pub fn post_save(&self, path: &str, bytes: &[u8]) -> bool {
|
||||
let name = file_name(path);
|
||||
let host_file = self.host_file.borrow().clone();
|
||||
let save_as = crate::hostmode::save_as(&name, host_file.as_deref());
|
||||
let save_as = !self.confirms_saves && self.saves.borrow().save_as(&name);
|
||||
let sent = self.host.post_save(&name, bytes, None, save_as).is_ok();
|
||||
// After a Save As hand-over the host has the new file: the next Save of it sends its name
|
||||
// with `saveAs: false`. A failed send changes nothing, so a retry is still a Save As.
|
||||
if sent && save_as {
|
||||
*self.host_file.borrow_mut() = Some(name);
|
||||
self.saves.borrow_mut().adopt(&name);
|
||||
}
|
||||
sent
|
||||
}
|
||||
|
||||
/// Hand the host the document's own file (Save, Save As) as `file`. To a host that confirms
|
||||
/// saves it goes with an `id` and stays unsaved until the host answers ([`Delivery::Pending`]);
|
||||
/// otherwise as [`post_save`](Self::post_save).
|
||||
pub fn post_document(&self, path: &str, bytes: &[u8], file: FileSnapshot, now_ms: u64, ctx: &egui::Context) -> Delivery {
|
||||
if !self.confirms_saves {
|
||||
return if self.post_save(path, bytes) { Delivery::Saved } else { Delivery::Refused };
|
||||
}
|
||||
let name = file_name(path);
|
||||
// Recorded before the post: a page host can answer while it is still dispatching.
|
||||
let (started, timeout_ms) = {
|
||||
let mut saves = self.saves.borrow_mut();
|
||||
(saves.start(&name, file, now_ms), saves.timeout_ms())
|
||||
};
|
||||
match self.host.post_save(&name, bytes, Some(&started.id), started.save_as) {
|
||||
Ok(()) => {
|
||||
// Schedule the timeout wakeup immediately so an idle tab still times out if the
|
||||
// host never answers after this frame.
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(timeout_ms));
|
||||
Delivery::Pending
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("couldn't hand {name} to the host: {e}");
|
||||
self.saves.borrow_mut().failed(&started.id);
|
||||
Delivery::Refused
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Report unsaved changes when they appear or go away, not every frame (the crate does not
|
||||
/// repeat a state it already reported).
|
||||
pub fn set_dirty(&self, dirty: bool) {
|
||||
@@ -118,23 +211,33 @@ impl Bridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an open message carries, queued for the app's own open path, or nothing when the
|
||||
/// payload isn't one (a `File` the app doesn't read, or over the open limit).
|
||||
fn deliver_open(opens: &OpenQueue, ctx: &egui::Context, host_file: &RefCell<Option<String>>, name: &str, data: &FileData) {
|
||||
/// The app's own open queue gets a file the host sent: the same "Opening as a new file" card as a
|
||||
/// dropped file, and `file.open` with the contents once read.
|
||||
fn queue_open(fig: &mut FigApp, name: String, bytes: Vec<u8>) {
|
||||
let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes)));
|
||||
fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen {
|
||||
label: name.clone(),
|
||||
params: serde_json::json!({ "name": name }),
|
||||
command: "file.open",
|
||||
target: None,
|
||||
read: Some(read),
|
||||
});
|
||||
}
|
||||
|
||||
/// The file an open message carries, copied out for the next frame, or nothing when the payload
|
||||
/// isn't one (a `File` the app doesn't read, or over the open limit). Once handled it is the
|
||||
/// document's file: a Save of it under this name is `saveAs: false`.
|
||||
fn open_bytes(name: &str, data: &FileData) -> Option<FromHost> {
|
||||
let name = crate::hostmode::open_name(name);
|
||||
let FileData::Bytes(array) = data else {
|
||||
log::warn!("host file {name} came as a File; FigCraft reads bytes only; not opened");
|
||||
return;
|
||||
return None;
|
||||
};
|
||||
if figcraft_ui_egui::browser_can_read(&name, data.size()).is_err() {
|
||||
log::warn!("host file {name} is too large to open in the browser; not opened");
|
||||
return;
|
||||
return None;
|
||||
}
|
||||
// The document's file is now the one the host sent: a Save of it under this name is
|
||||
// `saveAs: false`.
|
||||
*host_file.borrow_mut() = Some(name.clone());
|
||||
opens.borrow_mut().push((name, array.to_vec()));
|
||||
ctx.request_repaint();
|
||||
Some(FromHost::Open(name, array.to_vec()))
|
||||
}
|
||||
|
||||
/// The last component of `path`, or the whole of it when there is none.
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Confirmed saves: what the bridge ([`crate::host`]) knows about the files it handed a host page,
|
||||
//! kept apart from the browser so every step is testable without one (like [`crate::hostmode`]).
|
||||
//!
|
||||
//! A host that confirms saves (`?save=managed`, [`crate::query::confirms_saves`]) gets each
|
||||
//! Save and Save As of the document with an `id` and answers `saved` with that `id` once it stored
|
||||
//! the file. Until then the document keeps its unsaved changes. Only one document save waits at a
|
||||
//! time: a newer one replaces it, and an answer for any other `id` (an older save, a repeat, one
|
||||
//! the host made up) is ignored. A save the host doesn't answer within the timeout counts as not
|
||||
//! stored. A file the host opens forgets the save still waiting, so a late answer can't touch
|
||||
//! the file opened since.
|
||||
//!
|
||||
//! The file the host opened, or the one the last Save As made, is kept here too: a Save As becomes
|
||||
//! the document's file only once the host confirms it, so after a failed one the next Save is
|
||||
//! still a Save As.
|
||||
|
||||
/// How long a document save waits for the host's answer before it counts as not stored.
|
||||
pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
|
||||
|
||||
/// A document save handed to the host and not answered yet.
|
||||
#[derive(Debug)]
|
||||
pub struct PendingSave<F> {
|
||||
/// The `id` the save carried; the host's `saved` names it.
|
||||
pub id: String,
|
||||
/// The file name it went out under.
|
||||
pub name: String,
|
||||
/// It went out as `saveAs: true`: confirmed, it becomes the document's file.
|
||||
pub save_as: bool,
|
||||
/// When it was handed over, in the caller's clock (milliseconds).
|
||||
pub started_at_ms: u64,
|
||||
/// The document as handed over. In the app this is its `FileSnapshot` (the tab's uid, its
|
||||
/// revision and contents), which marks the document saved as of the snapshot once confirmed.
|
||||
pub file: F,
|
||||
}
|
||||
|
||||
/// A document save just handed to [`HostSaves::start`]: what to post with it.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Started {
|
||||
pub id: String,
|
||||
pub save_as: bool,
|
||||
}
|
||||
|
||||
/// The bridge's record of the document's file and the save waiting for the host.
|
||||
#[derive(Debug)]
|
||||
pub struct HostSaves<F> {
|
||||
host_file: Option<String>,
|
||||
/// The number in the next save's `id`. Never reset, so an `id` is never used twice on a page.
|
||||
next_id: u64,
|
||||
pending: Option<PendingSave<F>>,
|
||||
timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl<F> Default for HostSaves<F> {
|
||||
fn default() -> Self {
|
||||
Self::new(DEFAULT_TIMEOUT_MS)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> HostSaves<F> {
|
||||
pub fn new(timeout_ms: u64) -> Self {
|
||||
Self { host_file: None, next_id: 1, pending: None, timeout_ms }
|
||||
}
|
||||
|
||||
/// How long a save waits for its answer, in milliseconds.
|
||||
pub fn timeout_ms(&self) -> u64 {
|
||||
self.timeout_ms
|
||||
}
|
||||
|
||||
/// The file the host opened, or the one the last confirmed (or, without confirmation, posted)
|
||||
/// Save As made.
|
||||
pub fn host_file(&self) -> Option<&str> {
|
||||
self.host_file.as_deref()
|
||||
}
|
||||
|
||||
/// Whether a file named `name` goes out as `saveAs: true` now ([`crate::hostmode::save_as`]).
|
||||
pub fn save_as(&self, name: &str) -> bool {
|
||||
crate::hostmode::save_as(name, self.host_file.as_deref())
|
||||
}
|
||||
|
||||
/// A Save As went to a host that doesn't confirm saves: `name` is the document's file now.
|
||||
pub fn adopt(&mut self, name: &str) {
|
||||
self.host_file = Some(name.to_string());
|
||||
}
|
||||
|
||||
/// The host sent the file `name` to open: it is the document's file now. A save still waiting
|
||||
/// was for the document open before, so it is forgotten and returned; its answer, if one
|
||||
/// comes, is ignored, and that document keeps its unsaved changes.
|
||||
pub fn opened(&mut self, name: &str) -> Option<PendingSave<F>> {
|
||||
self.host_file = Some(name.to_string());
|
||||
self.pending.take()
|
||||
}
|
||||
|
||||
/// A Save or Save As of the document as `file`, under `name`, handed over at `now_ms`: the `id`
|
||||
/// and `saveAs` to post it with. A save still waiting is replaced, so its answer is ignored.
|
||||
pub fn start(&mut self, name: &str, file: F, now_ms: u64) -> Started {
|
||||
let id = format!("save-{}", self.next_id);
|
||||
self.next_id += 1;
|
||||
let save_as = self.save_as(name);
|
||||
self.pending = Some(PendingSave { id: id.clone(), name: name.to_string(), save_as, started_at_ms: now_ms, file });
|
||||
Started { id, save_as }
|
||||
}
|
||||
|
||||
/// The host's `saved` for `id`: the save it confirms, when that is the one waiting. A Save As
|
||||
/// becomes the document's file now. Any other `id` changes nothing.
|
||||
pub fn saved(&mut self, id: &str) -> Option<PendingSave<F>> {
|
||||
let save = self.take(id)?;
|
||||
if save.save_as {
|
||||
self.host_file = Some(save.name.clone());
|
||||
}
|
||||
Some(save)
|
||||
}
|
||||
|
||||
/// The save `id` could not be stored (the post failed, or the host refused it): the save,
|
||||
/// when that is the one waiting. The document's file stays as it was. Any other `id` changes
|
||||
/// nothing.
|
||||
pub fn failed(&mut self, id: &str) -> Option<PendingSave<F>> {
|
||||
self.take(id)
|
||||
}
|
||||
|
||||
/// The save waiting since longer than the timeout at `now_ms`, which then counts as failed.
|
||||
pub fn expire(&mut self, now_ms: u64) -> Option<PendingSave<F>> {
|
||||
let waiting = self.pending.as_ref()?;
|
||||
if now_ms.saturating_sub(waiting.started_at_ms) < self.timeout_ms {
|
||||
return None;
|
||||
}
|
||||
self.pending.take()
|
||||
}
|
||||
|
||||
/// How long from `now_ms` until the waiting save times out (so the app wakes then), or
|
||||
/// `None` when none waits.
|
||||
pub fn wait_ms(&self, now_ms: u64) -> Option<u64> {
|
||||
let waiting = self.pending.as_ref()?;
|
||||
Some((waiting.started_at_ms.saturating_add(self.timeout_ms)).saturating_sub(now_ms))
|
||||
}
|
||||
|
||||
fn take(&mut self, id: &str) -> Option<PendingSave<F>> {
|
||||
if self.pending.as_ref().is_some_and(|p| p.id == id) { self.pending.take() } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The document as handed over: in these tests, a label for the revision saved.
|
||||
type Saves = HostSaves<&'static str>;
|
||||
|
||||
fn opened(name: &str) -> Saves {
|
||||
let mut saves = Saves::default();
|
||||
assert!(saves.opened(name).is_none());
|
||||
saves
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_save_gets_an_id_of_its_own() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let first = saves.start("Poster.figcraft", "r1", 0).id;
|
||||
let second = saves.start("Poster.figcraft", "r2", 0).id;
|
||||
assert_ne!(first, second);
|
||||
saves.opened("Other.figcraft");
|
||||
let third = saves.start("Other.figcraft", "r3", 0).id;
|
||||
assert!(third != first && third != second, "opening a file doesn't start the ids over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_confirmed_save_hands_back_what_was_saved() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let started = saves.start("Poster.figcraft", "r1", 5);
|
||||
assert!(!started.save_as, "a Save of the host's own file");
|
||||
let save = saves.saved(&started.id).expect("the waiting save");
|
||||
assert_eq!((save.file, save.name.as_str(), save.started_at_ms), ("r1", "Poster.figcraft", 5));
|
||||
assert!(saves.wait_ms(5).is_none(), "nothing waits any more");
|
||||
assert!(saves.saved(&started.id).is_none(), "a repeated answer changes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_as_becomes_the_document_s_file_only_once_confirmed() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let started = saves.start("Poster 2.figcraft", "r1", 0);
|
||||
assert!(started.save_as);
|
||||
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "not before the host stored it");
|
||||
saves.saved(&started.id);
|
||||
assert_eq!(saves.host_file(), Some("Poster 2.figcraft"));
|
||||
assert!(!saves.start("Poster 2.figcraft", "r2", 0).save_as, "the next Save is of that file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_save_as_leaves_the_document_s_file_so_a_retry_is_still_a_save_as() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let started = saves.start("Poster 2.figcraft", "r1", 0);
|
||||
let save = saves.failed(&started.id).expect("the waiting save");
|
||||
assert_eq!(save.file, "r1");
|
||||
assert_eq!(saves.host_file(), Some("Poster.figcraft"));
|
||||
assert!(saves.start("Poster 2.figcraft", "r1", 0).save_as);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_for_other_ids_change_nothing() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let started = saves.start("Poster 2.figcraft", "r1", 0);
|
||||
for id in ["", "save-0", "save-99", "Save-1 ", "nonsense"] {
|
||||
assert!(saves.saved(id).is_none(), "{id:?}");
|
||||
assert!(saves.failed(id).is_none(), "{id:?}");
|
||||
}
|
||||
assert_eq!(saves.host_file(), Some("Poster.figcraft"));
|
||||
assert!(saves.saved(&started.id).is_some(), "the real answer still counts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_save_replaces_the_one_waiting() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let older = saves.start("Poster 2.figcraft", "r1", 0);
|
||||
let newer = saves.start("Poster.figcraft", "r2", 10);
|
||||
assert!(saves.saved(&older.id).is_none(), "a late answer for the older save is ignored");
|
||||
assert!(saves.failed(&older.id).is_none());
|
||||
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "the older Save As never became the file");
|
||||
assert_eq!(saves.saved(&newer.id).map(|s| s.file), Some("r2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_save_left_unanswered_times_out() {
|
||||
let mut saves = Saves::new(1_000);
|
||||
saves.opened("Poster.figcraft");
|
||||
let started = saves.start("Poster 2.figcraft", "r1", 100);
|
||||
assert!(saves.expire(100).is_none());
|
||||
assert!(saves.expire(1_099).is_none(), "still inside the timeout");
|
||||
let remaining = saves.wait_ms(600).expect("a save waits");
|
||||
assert!(remaining > 0 && remaining < saves.timeout_ms(), "{remaining}");
|
||||
let save = saves.expire(1_100).expect("timed out");
|
||||
assert_eq!(save.file, "r1");
|
||||
assert_eq!(saves.host_file(), Some("Poster.figcraft"), "a timed-out Save As isn't the file");
|
||||
assert!(saves.saved(&started.id).is_none(), "an answer after the timeout is ignored");
|
||||
assert!(saves.expire(5_000).is_none() && saves.wait_ms(5_000).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_that_goes_back_does_not_end_the_wait_early() {
|
||||
let mut saves = Saves::new(1_000);
|
||||
saves.start("Untitled.figcraft", "r1", 500);
|
||||
assert!(saves.expire(0).is_none());
|
||||
assert!(saves.wait_ms(0).is_some_and(|w| w >= saves.timeout_ms()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_file_forgets_the_save_still_waiting() {
|
||||
let mut saves = opened("Poster.figcraft");
|
||||
let started = saves.start("Poster 2.figcraft", "r1", 0);
|
||||
let dropped = saves.opened("Other.figcraft").expect("the save that waited");
|
||||
assert_eq!(dropped.file, "r1");
|
||||
assert!(saves.saved(&started.id).is_none(), "its late answer is ignored");
|
||||
assert_eq!(saves.host_file(), Some("Other.figcraft"), "and can't rename the file opened since");
|
||||
assert!(saves.expire(u64::MAX).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_confirmation_a_save_as_is_the_document_s_file_once_posted() {
|
||||
let mut saves = Saves::default();
|
||||
assert!(saves.save_as("Untitled.figcraft"), "the host never sent a file");
|
||||
saves.adopt("Untitled.figcraft");
|
||||
assert!(!saves.save_as("Untitled.figcraft"));
|
||||
assert!(!saves.save_as("Untitled.png"), "an export is never the document's file");
|
||||
}
|
||||
}
|
||||
@@ -21,13 +21,14 @@
|
||||
//! `http://` on a trusted network to reach plain `ws://` hosts on other machines.
|
||||
//! - host mode: `?host=parent` (a same-origin page embedding FigCraft in an `<iframe>`) or
|
||||
//! `data-host="page"` on the canvas (the page's own document) hands the page the app's files
|
||||
//! instead of downloading them and reports unsaved changes (`host`);
|
||||
//! instead of downloading them and reports unsaved changes (`host`); with `?save=managed` (or
|
||||
//! `data-save="managed"`) a document save waits for the page's confirmation (`host_saves`);
|
||||
//!
|
||||
//! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?control` installs
|
||||
//! `window.figcraft`, the page's control channel (`api.rs`), which is off without it; `?host=parent`
|
||||
//! (inside an `<iframe>`) talks to a same-origin parent page instead: it sends the document to open
|
||||
//! and stores what FigCraft saves. `&author=` names the user for comments and board notes in either
|
||||
//! host mode.
|
||||
//! host mode, and `&save=managed` makes document saves wait for the host's `saved`.
|
||||
//!
|
||||
//! URL fragment: `#join=<invite link or join code>` joins that live session once the page has
|
||||
//! loaded, so a bookmark opens a shared file. `join` takes the rest of the fragment: put it last.
|
||||
@@ -39,6 +40,8 @@ mod api;
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod host;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod host_saves;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod hostmode;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
mod kept;
|
||||
|
||||
@@ -38,3 +38,11 @@ pub fn page_server(content: &str) -> Option<String> {
|
||||
pub fn control(search: &str) -> bool {
|
||||
search.strip_prefix('?').unwrap_or(search).split('&').any(|entry| entry.split('=').next() == Some("control"))
|
||||
}
|
||||
|
||||
/// Whether the host confirms saves ([`crate::host_saves`]): `search` (`location.search`, with or
|
||||
/// without its `?`) has exactly `save=managed`, or the canvas has `data-save="managed"` (a page
|
||||
/// running FigCraft in its own document). Without either, a file counts as saved once it is
|
||||
/// handed to the host, as before.
|
||||
pub fn confirms_saves(search: &str, data_save: Option<&str>) -> bool {
|
||||
search.strip_prefix('?').unwrap_or(search).split('&').any(|entry| entry == "save=managed") || data_save == Some("managed")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! `#join=` and `?control` in the page's URL, and the server the page names for itself.
|
||||
//! `#join=`, `?control` and `?save=managed` in the page's URL, and the server the page names for
|
||||
//! itself.
|
||||
|
||||
use crate::query::{control, join_link, page_server};
|
||||
use crate::query::{confirms_saves, control, join_link, page_server};
|
||||
|
||||
#[test]
|
||||
fn join_takes_the_rest_of_the_fragment() {
|
||||
@@ -82,3 +83,14 @@ fn a_page_rejects_server_delimiters_that_endpoint_parsing_would_strip() {
|
||||
assert_eq!(page_server(&server), None, "{server:?} must not replace the default server");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confirmed_saves_are_opt_in() {
|
||||
assert!(confirms_saves("?host=parent&save=managed", None));
|
||||
assert!(confirms_saves("save=managed", None), "no leading ?");
|
||||
assert!(confirms_saves("", Some("managed")), "a page host's canvas attribute");
|
||||
for search in ["", "?host=parent", "?save", "?save=", "?save=auto", "?save=managedx", "?xsave=managed", "?save=Managed"] {
|
||||
assert!(!confirms_saves(search, None), "{search:?}");
|
||||
}
|
||||
assert!(!confirms_saves("?host=parent", Some("auto")));
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
//! The browser shell: web `Services` and the eframe web runner.
|
||||
|
||||
use figcraft_engine::Session;
|
||||
use figcraft_ui_egui::{ContentsFuture, FigApp, Services};
|
||||
use figcraft_engine::cmd::file::FileSnapshot;
|
||||
use figcraft_ui_egui::{ContentsFuture, Delivery, FigApp, Services};
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
const CANVAS_ID: &str = "figcraft_canvas";
|
||||
@@ -36,11 +37,11 @@ pub fn start() {
|
||||
// documents in it and stores what it saves (`host`); unframed there is no parent, so that URL
|
||||
// on its own stays the normal app with downloads. `data-host="page"` on the canvas opts a
|
||||
// page in instead: it runs FigCraft in its own document and talks over DOM `CustomEvent`s on
|
||||
// the canvas.
|
||||
let bridge = crate::host::Bridge::connect(&canvas);
|
||||
// the canvas. `?save=managed` (or `data-save="managed"` on the canvas) opts the host in to
|
||||
// confirmed saves: a document save waits for its `saved` (`host_saves`).
|
||||
let confirms_saves = crate::query::confirms_saves(&query(), canvas.get_attribute("data-save").as_deref());
|
||||
let bridge = crate::host::Bridge::connect(&canvas, confirms_saves);
|
||||
let app_bridge = bridge.clone();
|
||||
// Files the host sends, on their way into the app's own open queue each frame.
|
||||
let opens: crate::host::OpenQueue = std::rc::Rc::default();
|
||||
let mut options = eframe::WebOptions::default();
|
||||
// `?webgl`: force the WebGL2 backend (troubleshooting, and headless browsers whose WebGPU
|
||||
// adapter request returns nothing).
|
||||
@@ -101,9 +102,9 @@ pub fn start() {
|
||||
}
|
||||
// The host's files arrive on the app's own open path (a dropped file's).
|
||||
if let Some(bridge) = &app_bridge {
|
||||
bridge.listen(opens.clone(), cc.egui_ctx.clone());
|
||||
bridge.listen(cc.egui_ctx.clone());
|
||||
}
|
||||
Ok(Box::new(WebShell { fig, host: app_bridge, opens }))
|
||||
Ok(Box::new(WebShell { fig, host: app_bridge }))
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
@@ -169,6 +170,12 @@ fn page_meta(name: &str) -> Option<String> {
|
||||
document.query_selector(&format!("meta[name=\"{name}\"]")).ok().flatten()?.get_attribute("content")
|
||||
}
|
||||
|
||||
/// The clock confirmed saves time out by (milliseconds; `Date.now()`, which
|
||||
/// [`crate::host_saves`] tolerates going back).
|
||||
fn now_ms() -> u64 {
|
||||
js_sys::Date::now().max(0.0) as u64
|
||||
}
|
||||
|
||||
fn query() -> String {
|
||||
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
|
||||
}
|
||||
@@ -181,31 +188,22 @@ struct WebShell {
|
||||
fig: FigApp,
|
||||
/// The host bridge, when the page hosts the app (`?host=parent` or `data-host="page"`).
|
||||
host: Option<crate::host::Bridge>,
|
||||
/// Files the host sent, waiting to join the app's own open queue.
|
||||
opens: crate::host::OpenQueue,
|
||||
}
|
||||
|
||||
impl eframe::App for WebShell {
|
||||
// eframe runs `logic` for visible tabs and, with only `run_logic`, for hidden ones: keep
|
||||
// autosave/live/control deadlines moving without a paint. `FigApp::ui` does not repeat it.
|
||||
/// Run the browser shell's eframe logic callback: hand the host's files to the app's open
|
||||
/// queue, guard `background_tick` so hidden tabs still advance autosave, live and control
|
||||
/// deadlines without painting, and report unsaved changes to the host. `FigApp::ui` does
|
||||
/// not repeat it.
|
||||
/// Run the browser shell's eframe logic callback: handle what the host sent (its files join
|
||||
/// the app's open queue, its save confirmations mark documents saved), guard `background_tick`
|
||||
/// so hidden tabs still advance autosave, live and control deadlines without painting, and
|
||||
/// report unsaved changes to the host. `FigApp::ui` does not repeat it.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
// Every frame, hidden or not, starts here: what the last one left is what a panic keeps.
|
||||
UNSAVED.with(|u| u.try_borrow_mut().map(|mut u| u.follow(&self.fig.session))).ok();
|
||||
// Files the host sent join the app's own open queue (a dropped file's): the same
|
||||
// "Opening as a new file" card, and `file.open` with the contents once read.
|
||||
for (name, bytes) in std::mem::take(&mut *self.opens.borrow_mut()) {
|
||||
let read: figcraft_ui_egui::ReadFuture = Box::pin(std::future::ready(Ok(bytes)));
|
||||
self.fig.ui.pending_opens.push(figcraft_ui_egui::pending_open::PendingOpen {
|
||||
label: name.clone(),
|
||||
params: serde_json::json!({ "name": name }),
|
||||
command: "file.open",
|
||||
target: None,
|
||||
read: Some(read),
|
||||
});
|
||||
// Files the host sent join the app's own open queue (a dropped file's), and its answers to
|
||||
// confirmed saves land, in the order they came (crate::host).
|
||||
if let Some(bridge) = &self.host {
|
||||
bridge.frame(&mut self.fig, ctx, now_ms());
|
||||
}
|
||||
figcraft_ui_egui::windows::guard(&mut self.fig, ctx, |fig| fig.background_tick(ctx));
|
||||
// The host hears when unsaved changes appear or go away (crate::host).
|
||||
@@ -282,6 +280,18 @@ impl Services for WebServices {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The document's own file (Save, Save As): as [`download`](Self::download), except that a
|
||||
/// host that confirms saves gets it with an `id` and it stays unsaved until the host answers
|
||||
/// ([`crate::host`]).
|
||||
fn deliver_document(&mut self, name: &str, bytes: &[u8], file: FileSnapshot) -> Delivery {
|
||||
if crate::api::capture(name, bytes) {
|
||||
return Delivery::Saved;
|
||||
}
|
||||
if let Some(bridge) = &self.host {
|
||||
return bridge.post_document(name, bytes, file, now_ms(), &self.ctx);
|
||||
}
|
||||
if self.download(name, bytes) { Delivery::Saved } else { Delivery::Refused }
|
||||
}
|
||||
fn host_file(&self) -> Option<String> {
|
||||
self.host.as_ref()?.host_file()
|
||||
}
|
||||
|
||||
@@ -21,6 +21,9 @@ figcraft-text = { workspace = true }
|
||||
craft-window = { workspace = true }
|
||||
# The suite's settings folder: `FIGCRAFT_CONFIG_DIR`, a portable marker, then the platform folder.
|
||||
craft-settings = { workspace = true }
|
||||
# The control channel's token and the ArtCraft Launcher's agents switch (src/agents.rs).
|
||||
craft-control = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
egui = { workspace = true }
|
||||
# `links`: without it eframe drops every `ctx.open_url` and hyperlink click (the update prompt's
|
||||
# What's new and Download, About, Credits) with only a log warning.
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! AI agents in the open window, through the ArtCraft Launcher's switch (#2740): while the
|
||||
//! launcher's *Let AI agents use Craft apps* names FigCraft (with the suite's `AI-MCP` flag), the
|
||||
//! app serves its control channel on a free loopback port with a token in an owner-only file and
|
||||
//! publishes `agent-connection.json` in its settings folder, where `figcraft-cli mcp` finds it.
|
||||
//! When the switch turns off, the listener stops and the file goes, with no restart. FigCraft has
|
||||
//! no agents switch of its own: the launcher's is the person's consent for every Craft app. What
|
||||
//! agents ask for there is confined to the agent folder (`Documents/ArtCraft/Agents/FigCraft`),
|
||||
//! unless the app was started with automation roots of its own, which then apply.
|
||||
//!
|
||||
//! `--control PORT` still opens the channel on that port for scripts ([`serve_port`]), with a token
|
||||
//! too.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::net::TcpListener;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use craft_control::agents::{self, AgentSwitch, Connection};
|
||||
use craft_control::auth;
|
||||
use figcraft_engine::file_access::Roots;
|
||||
|
||||
use crate::control_server::Running;
|
||||
|
||||
/// FigCraft's id in the ArtCraft Launcher's catalog and app list.
|
||||
pub const LAUNCHER_APP_ID: &str = "figcraft";
|
||||
/// The app's name in the connection file and in messages.
|
||||
const APP_NAME: &str = "FigCraft";
|
||||
/// The port in messages about `--control`; agents get any free port, named in the connection file.
|
||||
const DEFAULT_PORT: u16 = 7979;
|
||||
|
||||
/// Where FigCraft's token files live and which environment it reads (`FIGCRAFT_CONTROL_DIR`,
|
||||
/// `FIGCRAFT_CONTROL_TOKEN`). `figcraft-cli` describes the same app.
|
||||
pub fn control_app() -> auth::App {
|
||||
auth::App { name: APP_NAME, data_dir: crate::services::config_dir, env, utc, default_port: DEFAULT_PORT }
|
||||
}
|
||||
|
||||
fn env(name: &str) -> Option<OsString> {
|
||||
std::env::var_os(format!("FIGCRAFT_{name}"))
|
||||
}
|
||||
|
||||
fn utc(secs: u64) -> String {
|
||||
i64::try_from(secs)
|
||||
.ok()
|
||||
.and_then(|s| chrono::DateTime::from_timestamp(s, 0))
|
||||
.map_or_else(|| format!("{secs} s after 1970"), |t| t.format("%Y-%m-%d %H:%M:%S UTC").to_string())
|
||||
}
|
||||
|
||||
/// The token this launch serves with: the one set on purpose in `FIGCRAFT_CONTROL_TOKEN`, else a
|
||||
/// new random one.
|
||||
fn launch_token(app: &auth::App) -> Option<String> {
|
||||
app.env_token().or_else(craft_control::server::new_token)
|
||||
}
|
||||
|
||||
/// What serves a bound listener with a token, its requests confined to the roots given (the app's
|
||||
/// control server; a fake in tests).
|
||||
pub type Serve<'a> = &'a mut dyn FnMut(TcpListener, String, Option<Arc<Roots>>) -> std::io::Result<Running>;
|
||||
|
||||
/// Writes a token file readable only by the user ([`auth::App::write_token_file`]). On Windows that
|
||||
/// starts a system tool, which in a test binary disturbs the sockets of tests running beside it,
|
||||
/// so the tests write a plain file instead.
|
||||
type WriteToken = fn(&auth::App, &Path, &str) -> std::io::Result<()>;
|
||||
|
||||
fn owner_only(app: &auth::App, path: &Path, token: &str) -> std::io::Result<()> {
|
||||
app.write_token_file(path, token)
|
||||
}
|
||||
|
||||
/// `--control PORT`: bind the port (waiting up to `busy` while an ending launch still holds it),
|
||||
/// then write this launch's token file and serve. Binding first means a second launch on a taken
|
||||
/// port never replaces the running app's token. A token that can't be written leaves the channel
|
||||
/// off.
|
||||
pub fn serve_port(port: u16, busy: Duration, serve: Serve) -> Result<Running, String> {
|
||||
serve_port_with(&control_app(), owner_only, port, busy, serve)
|
||||
}
|
||||
|
||||
/// [`serve_port`] for `app`'s token files, written with `write_token`.
|
||||
fn serve_port_with(app: &auth::App, write_token: WriteToken, port: u16, busy: Duration, serve: Serve) -> Result<Running, String> {
|
||||
let listener = crate::control_server::bind(port, busy)
|
||||
.map_err(|e| format!("can't bind 127.0.0.1:{port}: {e} (another app may own it; pick another port)"))?;
|
||||
let token = launch_token(app).ok_or("no random token could be made, so the channel stays off")?;
|
||||
let file = app.token_path(port).ok_or("no settings folder for the token file, so the channel stays off")?;
|
||||
write_token(app, &file, &token).map_err(|e| format!("can't write the token file {}: {e}, so the channel stays off", file.display()))?;
|
||||
// The app's own roots, if it was started with any, confine `--control` as before.
|
||||
serve(listener, token, None).map_err(|e| format!("can't start the control server: {e}"))
|
||||
}
|
||||
|
||||
/// The listener the launcher's switch turns on and off.
|
||||
struct Listening {
|
||||
running: Running,
|
||||
token_file: PathBuf,
|
||||
token: String,
|
||||
}
|
||||
|
||||
/// The launcher's switch for FigCraft and the listener it governs.
|
||||
pub struct Agents {
|
||||
switch: AgentSwitch,
|
||||
/// The settings folder: connection file and token file.
|
||||
dir: PathBuf,
|
||||
listening: Option<Listening>,
|
||||
/// The last start failed: tried again only after the switch has been off.
|
||||
failed: bool,
|
||||
write_token: WriteToken,
|
||||
/// The folder agents' requests are confined to; `None` when the app was started with
|
||||
/// automation roots of its own, which apply instead.
|
||||
folder: Option<PathBuf>,
|
||||
/// The app has no roots of its own, and no agent folder could be found: agents stay out.
|
||||
no_folder: bool,
|
||||
}
|
||||
|
||||
impl Agents {
|
||||
/// Watch the launcher's switch, removing a connection file a crashed launch left in `dir`;
|
||||
/// `wake` asks the window for a frame, where [`Self::tick`] sees the change. `own_roots`: the
|
||||
/// app was started with automation roots, which confine agents too.
|
||||
pub fn watch(dir: PathBuf, own_roots: bool, wake: impl Fn() + Send + 'static) -> Self {
|
||||
agents::remove_stale_connection(&dir);
|
||||
let mut agents = Self::with_switch(dir, AgentSwitch::watch(LAUNCHER_APP_ID, wake));
|
||||
if !own_roots {
|
||||
agents.folder = agents::default_folder(APP_NAME);
|
||||
agents.no_folder = agents.folder.is_none();
|
||||
}
|
||||
agents
|
||||
}
|
||||
|
||||
fn with_switch(dir: PathBuf, switch: AgentSwitch) -> Self {
|
||||
Self { switch, dir, listening: None, failed: false, write_token: owner_only, folder: None, no_folder: false }
|
||||
}
|
||||
|
||||
/// The roots agents' requests are confined to: the agent folder, made when missing.
|
||||
fn roots(&self) -> Result<Option<Arc<Roots>>, String> {
|
||||
if self.no_folder {
|
||||
return Err("no Documents folder for the agent folder, so agents stay out".into());
|
||||
}
|
||||
let Some(folder) = &self.folder else { return Ok(None) };
|
||||
std::fs::create_dir_all(folder).map_err(|e| format!("can't make the agent folder {}: {e}", folder.display()))?;
|
||||
let folder = [folder.display().to_string()];
|
||||
Ok(Some(Arc::new(Roots::new(&folder, &folder)?)))
|
||||
}
|
||||
|
||||
/// Follow the switch: start listening when it allows agents, stop when it doesn't. Cheap
|
||||
/// enough for every frame (one atomic read while nothing changes).
|
||||
pub fn tick(&mut self, serve: Serve) {
|
||||
let allowed = self.switch.allows(false);
|
||||
if !allowed {
|
||||
self.failed = false;
|
||||
self.stop();
|
||||
} else if self.listening.is_none() && !self.failed {
|
||||
match self.start(serve) {
|
||||
Ok(l) => {
|
||||
log::info!("agents: listening on 127.0.0.1:{} for the ArtCraft Launcher's agents", l.running.port());
|
||||
self.listening = Some(l);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("agents: {e}");
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start(&self, serve: Serve) -> Result<Listening, String> {
|
||||
let roots = self.roots()?;
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(|e| format!("can't listen on loopback: {e}"))?;
|
||||
let port = listener.local_addr().map_err(|e| format!("the listener has no port: {e}"))?.port();
|
||||
let app = control_app();
|
||||
let token = launch_token(&app).ok_or("no random token could be made")?;
|
||||
let token_file = self.dir.join(agents::TOKEN_FILE);
|
||||
(self.write_token)(&app, &token_file, &token).map_err(|e| format!("can't write the token file {}: {e}", token_file.display()))?;
|
||||
let running = match serve(listener, token.clone(), roots) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
auth::remove_token_file(&token_file, &token);
|
||||
return Err(format!("can't start the control server: {e}"));
|
||||
}
|
||||
};
|
||||
if let Err(e) = agents::write_connection(&self.dir, &Connection::new(port, token_file.clone(), APP_NAME)) {
|
||||
running.stop();
|
||||
auth::remove_token_file(&token_file, &token);
|
||||
return Err(format!("can't write {}: {e}", self.dir.join(agents::CONNECTION_FILE).display()));
|
||||
}
|
||||
Ok(Listening { running, token_file, token })
|
||||
}
|
||||
|
||||
/// Stop listening and remove this launch's connection file and token file.
|
||||
pub fn stop(&mut self) {
|
||||
if let Some(l) = self.listening.take() {
|
||||
l.running.stop();
|
||||
agents::remove_connection(&self.dir, std::process::id());
|
||||
auth::remove_token_file(&l.token_file, &l.token);
|
||||
log::info!("agents: stopped listening");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Agents {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "agents_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,227 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use figcraft_engine::events::EventLog;
|
||||
use figcraft_engine::file_access::Access;
|
||||
use figcraft_ui_egui::ControlRequest;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("figcraft-agents-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
type Queue = Arc<Mutex<Vec<ControlRequest>>>;
|
||||
|
||||
/// A plain token file: the owner-only writer is craft-control's, tested there (see [`WriteToken`]).
|
||||
fn plain(_: &auth::App, path: &Path, token: &str) -> std::io::Result<()> {
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
std::fs::write(
|
||||
path,
|
||||
format!(
|
||||
"{token}
|
||||
"
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Agents`] in `dir` with `switch`, writing plain token files.
|
||||
fn agents_in(dir: &Path, switch: AgentSwitch) -> Agents {
|
||||
let mut agents = Agents::with_switch(dir.to_path_buf(), switch);
|
||||
agents.write_token = plain;
|
||||
agents
|
||||
}
|
||||
|
||||
/// The listeners a [`server`] started: set once each is gone.
|
||||
type Ended = Arc<Mutex<Vec<Arc<AtomicBool>>>>;
|
||||
|
||||
/// The real control server over `queue`, with no window to answer; `ended` collects whether each
|
||||
/// listener it starts is gone.
|
||||
fn server(queue: &Queue, ended: &Ended) -> impl FnMut(TcpListener, String, Option<Arc<Roots>>) -> std::io::Result<Running> + use<> {
|
||||
let (queue, ended) = (queue.clone(), ended.clone());
|
||||
move |listener, token, roots| {
|
||||
let running =
|
||||
crate::control_server::serve_listener(listener, token, roots, queue.clone(), Arc::new(Mutex::new(None)), Arc::new(EventLog::default()))?;
|
||||
ended.lock().unwrap().push(running.ended());
|
||||
Ok(running)
|
||||
}
|
||||
}
|
||||
|
||||
/// A switch the test flips: `set` changes what the launcher's list says, and returns once the
|
||||
/// watch has seen it.
|
||||
struct Flip {
|
||||
launcher: Arc<AtomicBool>,
|
||||
tick: mpsc::Sender<()>,
|
||||
woken: mpsc::Receiver<()>,
|
||||
}
|
||||
|
||||
impl Flip {
|
||||
fn new(on: bool) -> (Self, AgentSwitch) {
|
||||
let launcher = Arc::new(AtomicBool::new(on));
|
||||
let (tick, ticks) = mpsc::channel::<()>();
|
||||
let (wake, woken) = mpsc::channel::<()>();
|
||||
let probe = launcher.clone();
|
||||
let switch = AgentSwitch::watch_with(
|
||||
true,
|
||||
move || probe.load(Ordering::SeqCst),
|
||||
move || ticks.recv().is_ok(),
|
||||
move || {
|
||||
let _ = wake.send(());
|
||||
},
|
||||
);
|
||||
(Self { launcher, tick, woken }, switch)
|
||||
}
|
||||
|
||||
fn set(&self, on: bool) {
|
||||
self.launcher.store(on, Ordering::SeqCst);
|
||||
self.tick.send(()).unwrap();
|
||||
self.woken.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Send `line` on a new connection to `port` and read the reply.
|
||||
fn ask(port: u16, line: &Value) -> Value {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
writeln!(stream, "{line}").unwrap();
|
||||
let mut reply = String::new();
|
||||
BufReader::new(stream).read_line(&mut reply).unwrap();
|
||||
serde_json::from_str(&reply).unwrap()
|
||||
}
|
||||
|
||||
/// Wait until the listener whose flag is `ended` is gone. Probing its port instead could reach
|
||||
/// another test's listener that got the same number.
|
||||
fn closed(ended: &AtomicBool) -> bool {
|
||||
let until = std::time::Instant::now() + Duration::from_secs(5);
|
||||
while !ended.load(Ordering::SeqCst) {
|
||||
if std::time::Instant::now() > until {
|
||||
return false;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
// The launcher's switch on: the app listens, publishes where, and takes requests that carry the
|
||||
// token. Off: no listener, no connection file, no token file, without a restart.
|
||||
#[test]
|
||||
fn the_launchers_switch_turns_the_listener_and_its_files_on_and_off() {
|
||||
let dir = folder("switch");
|
||||
let queue: Queue = Arc::new(Mutex::new(Vec::new()));
|
||||
let ended: Ended = Arc::default();
|
||||
let mut serve = server(&queue, &ended);
|
||||
let (flip, switch) = Flip::new(false);
|
||||
let mut agents = agents_in(&dir, switch);
|
||||
let agent_folder = dir.join("Agents").join("FigCraft");
|
||||
agents.folder = Some(agent_folder.clone());
|
||||
|
||||
agents.tick(&mut serve);
|
||||
assert!(agents::read_connection(&dir).unwrap().is_none(), "the switch is off: nothing published");
|
||||
assert!(agents.listening.is_none());
|
||||
|
||||
flip.set(true);
|
||||
agents.tick(&mut serve);
|
||||
let connection = agents::read_connection(&dir).unwrap().expect("the connection file");
|
||||
assert_eq!(connection.pid, std::process::id());
|
||||
let token = std::fs::read_to_string(dir.join(agents::TOKEN_FILE)).unwrap().trim().to_string();
|
||||
assert_eq!(connection.token_file, dir.join(agents::TOKEN_FILE));
|
||||
|
||||
let refused = ask(connection.port, &json!({"id": 1, "method": "ui.inspect", "token": "not-the-token"}));
|
||||
assert_eq!(refused["ok"], json!(false), "a wrong token is refused: {refused}");
|
||||
assert!(queue.lock().unwrap().is_empty(), "nothing is queued for a wrong token");
|
||||
// The right token gets the request to the window's queue (no window answers it here).
|
||||
let port = connection.port;
|
||||
let asking = std::thread::spawn(move || ask(port, &json!({"id": 2, "method": "ui.inspect", "token": token, "timeoutMs": 1})));
|
||||
let _ = asking.join().unwrap();
|
||||
assert_eq!(queue.lock().unwrap().first().map(|r| r.method.clone()), Some("ui.inspect".into()));
|
||||
// The request is confined to the agent folder, made for it.
|
||||
let roots = queue.lock().unwrap()[0].roots.clone().expect("an agent's request carries its folder");
|
||||
assert!(agent_folder.is_dir());
|
||||
assert!(roots.check(&agent_folder.join("a.figcraft"), Access::Write).is_ok());
|
||||
assert!(roots.check(&dir.join("a.figcraft"), Access::Write).is_err(), "outside the agent folder is refused");
|
||||
|
||||
flip.set(false);
|
||||
agents.tick(&mut serve);
|
||||
assert!(agents::read_connection(&dir).unwrap().is_none(), "the connection file is gone");
|
||||
assert!(!dir.join(agents::TOKEN_FILE).exists(), "the token file is gone");
|
||||
let first = ended.lock().unwrap()[0].clone();
|
||||
assert!(closed(&first), "nothing listens once the switch is off");
|
||||
|
||||
// On again: a new listener and a new file.
|
||||
flip.set(true);
|
||||
agents.tick(&mut serve);
|
||||
assert!(agents::read_connection(&dir).unwrap().is_some());
|
||||
drop(agents);
|
||||
assert!(agents::read_connection(&dir).unwrap().is_none(), "a closing app removes its file");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// Without the suite's AI-MCP flag the launcher's list means nothing: no listener.
|
||||
#[test]
|
||||
fn without_the_flag_nothing_listens() {
|
||||
let dir = folder("no-flag");
|
||||
let queue: Queue = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut agents = agents_in(&dir, AgentSwitch::fixed(false, true));
|
||||
agents.tick(&mut server(&queue, &Arc::default()));
|
||||
assert!(agents.listening.is_none());
|
||||
assert!(agents::read_connection(&dir).unwrap().is_none());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// A start that fails isn't tried again every frame, and leaves no token file; once the switch has
|
||||
// been off, the next on tries again.
|
||||
#[test]
|
||||
fn a_failed_start_waits_for_the_switch_to_turn_off_and_on() {
|
||||
let dir = folder("failed");
|
||||
let tries = AtomicUsize::new(0);
|
||||
let mut failing = |_: TcpListener, _: String, _: Option<Arc<Roots>>| -> std::io::Result<Running> {
|
||||
tries.fetch_add(1, Ordering::SeqCst);
|
||||
Err(std::io::Error::other("no thread"))
|
||||
};
|
||||
let (flip, switch) = Flip::new(true);
|
||||
let mut agents = agents_in(&dir, switch);
|
||||
agents.tick(&mut failing);
|
||||
agents.tick(&mut failing);
|
||||
assert_eq!(tries.load(Ordering::SeqCst), 1, "one try while the switch stays on");
|
||||
assert!(!dir.join(agents::TOKEN_FILE).exists(), "a failed start leaves no token file");
|
||||
assert!(agents::read_connection(&dir).unwrap().is_none());
|
||||
flip.set(false);
|
||||
agents.tick(&mut failing);
|
||||
flip.set(true);
|
||||
agents.tick(&mut failing);
|
||||
assert_eq!(tries.load(Ordering::SeqCst), 2, "tried again after off and on");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn control_folder() -> Option<PathBuf> {
|
||||
Some(std::env::temp_dir().join(format!("figcraft-agents-port-{}", std::process::id())))
|
||||
}
|
||||
|
||||
fn no_env(_: &str) -> Option<OsString> {
|
||||
None
|
||||
}
|
||||
|
||||
// `--control PORT` binds before it writes the token file: a second launch on a port the first
|
||||
// holds fails without replacing the first one's token.
|
||||
#[test]
|
||||
fn a_second_launch_on_a_taken_port_keeps_the_first_ones_token() {
|
||||
let app = auth::App { name: APP_NAME, data_dir: control_folder, env: no_env, utc, default_port: DEFAULT_PORT };
|
||||
let queue: Queue = Arc::new(Mutex::new(Vec::new()));
|
||||
let mut serve = server(&queue, &Arc::default());
|
||||
let port = TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||||
let first = serve_port_with(&app, plain, port, Duration::ZERO, &mut serve).unwrap();
|
||||
let file = app.token_path(port).unwrap();
|
||||
let token = std::fs::read_to_string(&file).unwrap();
|
||||
assert!(serve_port_with(&app, plain, port, Duration::ZERO, &mut serve).is_err(), "the port is taken");
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), token, "the running app's token stays");
|
||||
first.stop();
|
||||
let _ = std::fs::remove_dir_all(control_folder().unwrap());
|
||||
}
|
||||
@@ -1,24 +1,49 @@
|
||||
//! Localhost JSON-lines control server: each line `{"id", "method", "params"}` is queued for the UI
|
||||
//! thread; the reply line `{"id", "ok", "result" | "error"}` is written when the frame handled it.
|
||||
//!
|
||||
//! Every connection's first line carries the launch's token (`"token"`, #480): the app writes it
|
||||
//! to a file only the user can read, and a client reads it from there (`craft_control::auth`), so
|
||||
//! other users and web pages can't drive the app.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use figcraft_engine::events::{self, EventLog};
|
||||
use figcraft_engine::file_access::Roots;
|
||||
use figcraft_ui_egui::{ControlReply, ControlRequest, RequestGate, RequestState};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
type Queue = Arc<Mutex<Vec<ControlRequest>>>;
|
||||
/// The gates of one listener's requests still waiting for the UI; [`Running::stop`] cancels them
|
||||
/// and closes the registry, after which no request is queued.
|
||||
type Waiting = Arc<Mutex<WaitingGates>>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct WaitingGates {
|
||||
closed: bool,
|
||||
gates: Vec<RequestGate>,
|
||||
}
|
||||
type CtxSlot = Arc<Mutex<Option<egui::Context>>>;
|
||||
|
||||
const MAX_LINE: usize = 32 * 1024 * 1024;
|
||||
/// Bytes of request lines all connections hold at once (#1111): a line is counted as it is read
|
||||
/// and until its reply is written, so eight clients can't make the app hold eight full lines.
|
||||
const MAX_IN_FLIGHT: usize = 64 * 1024 * 1024;
|
||||
const MAX_CONNECTIONS: usize = 8;
|
||||
const MAX_QUEUED_REQUESTS: usize = 8;
|
||||
const TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// The longest a request's `timeoutMs` can make it wait: a client can raise the wait, never lift it.
|
||||
const MAX_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// How long a new connection has to show the token. A client sends it with its first request, so a
|
||||
/// connection that stays silent this long is no client of ours and gives its slot back. Shorter in
|
||||
/// tests, so waiting it out holds no test thread for long.
|
||||
#[cfg(not(test))]
|
||||
const TOKEN_WAIT: Duration = Duration::from_secs(5);
|
||||
#[cfg(test)]
|
||||
const TOKEN_WAIT: Duration = Duration::from_millis(300);
|
||||
/// How long the accepting thread waits after a failed accept. Accepting can keep failing, for
|
||||
/// example while the process has no file descriptors left, and retrying at once would keep a
|
||||
/// core busy until it recovers.
|
||||
@@ -103,25 +128,82 @@ pub fn bind(port: u16, busy: Duration) -> std::io::Result<TcpListener> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(port: u16, busy: Duration, queue: Queue, ctx: CtxSlot, events: Arc<EventLog>) {
|
||||
let listener = match bind(port, busy) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!("control server: can't bind 127.0.0.1:{port}: {e} (another app may own it; pick another port)");
|
||||
eprintln!("FigCraft control server failed to bind port {port}: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
eprintln!("FigCraft control server listening on 127.0.0.1:{port}");
|
||||
let spawned = std::thread::Builder::new().name("figcraft-control".into()).spawn(move || {
|
||||
let mut workers = Vec::new();
|
||||
for stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
|
||||
spawn_connection(stream, queue.clone(), ctx.clone(), events.clone(), &mut workers, TIMEOUT);
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::error!("control server thread: {e}");
|
||||
/// A control server that is serving: [`Running::stop`] ends it.
|
||||
pub struct Running {
|
||||
port: u16,
|
||||
stop: Arc<AtomicBool>,
|
||||
/// Set once the accepting thread has dropped the listener and closed every connection.
|
||||
ended: Arc<AtomicBool>,
|
||||
waiting: Waiting,
|
||||
}
|
||||
|
||||
impl Running {
|
||||
/// The loopback port it listens on.
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Stop accepting and close every connection. Requests still queued are cancelled, so none runs
|
||||
/// after the stop (the UI drops cancelled requests); one the UI is running still finishes. The
|
||||
/// accepting thread is woken with a connection of its own, which it drops; not once its listener
|
||||
/// is gone, when another program may have the port.
|
||||
pub fn stop(&self) {
|
||||
let mut waiting = self.waiting.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
// Closed under the same lock a connection takes to queue: a request either was noted
|
||||
// before (and is cancelled here) or finds the registry closed.
|
||||
waiting.closed = true;
|
||||
for gate in waiting.gates.drain(..) {
|
||||
gate.cancel_if_open();
|
||||
}
|
||||
drop(waiting);
|
||||
if !self.stop.swap(true, Ordering::SeqCst) && !self.ended.load(Ordering::SeqCst) {
|
||||
let _ = TcpStream::connect_timeout(&std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), Duration::from_millis(500));
|
||||
}
|
||||
}
|
||||
|
||||
/// Set once the listener is gone (tests).
|
||||
#[cfg(test)]
|
||||
pub fn ended(&self) -> Arc<AtomicBool> {
|
||||
self.ended.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve `listener` with `token` on a thread of its own. Only a connection whose first line
|
||||
/// carries `token` gets its requests queued, each confined to `roots` when given (an agent's
|
||||
/// folders; otherwise the app's own roots apply).
|
||||
pub fn serve_listener(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
roots: Option<Arc<Roots>>,
|
||||
queue: Queue,
|
||||
ctx: CtxSlot,
|
||||
events: Arc<EventLog>,
|
||||
) -> std::io::Result<Running> {
|
||||
let port = listener.local_addr()?.port();
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stopped = stop.clone();
|
||||
let ended = Arc::new(AtomicBool::new(false));
|
||||
let done = ended.clone();
|
||||
let waiting: Waiting = Arc::default();
|
||||
let queued = waiting.clone();
|
||||
std::thread::Builder::new().name("figcraft-control".into()).spawn(move || {
|
||||
let mut workers = Vec::new();
|
||||
let budget = Arc::new(AtomicUsize::new(0));
|
||||
let token: Arc<str> = token.into();
|
||||
for stream in accepted(listener.incoming(), || std::thread::sleep(ACCEPT_RETRY)) {
|
||||
if stopped.load(Ordering::SeqCst) {
|
||||
break;
|
||||
}
|
||||
let gates = Gates { token: &token, roots: roots.as_ref(), waiting: &queued };
|
||||
spawn_connection(stream, gates, queue.clone(), ctx.clone(), events.clone(), &budget, &mut workers, TIMEOUT);
|
||||
}
|
||||
drop(listener);
|
||||
for worker in workers {
|
||||
let _ = worker.stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
done.store(true, Ordering::SeqCst);
|
||||
})?;
|
||||
Ok(Running { port, stop, ended, waiting })
|
||||
}
|
||||
|
||||
/// The connections `incoming` accepts, calling `wait` after each failed accept.
|
||||
@@ -129,45 +211,182 @@ fn accepted<T>(incoming: impl Iterator<Item = std::io::Result<T>>, mut wait: imp
|
||||
incoming.filter_map(move |stream| stream.map_err(|_| wait()).ok())
|
||||
}
|
||||
|
||||
/// Since when a connection has been waiting for its client (`None` while the UI runs one of its
|
||||
/// requests).
|
||||
type Idle = Arc<Mutex<Option<Instant>>>;
|
||||
|
||||
/// One connection's thread, a handle on its socket and since when it has been idle.
|
||||
struct Worker {
|
||||
thread: std::thread::JoinHandle<()>,
|
||||
stream: TcpStream,
|
||||
idle: Idle,
|
||||
}
|
||||
|
||||
/// What a listener asks of its connections: the token, the roots its requests run in, and where
|
||||
/// it notes the requests still waiting for the UI.
|
||||
struct Gates<'a> {
|
||||
token: &'a Arc<str>,
|
||||
roots: Option<&'a Arc<Roots>>,
|
||||
waiting: &'a Waiting,
|
||||
}
|
||||
|
||||
fn spawn_connection(
|
||||
stream: TcpStream,
|
||||
gates: Gates,
|
||||
queue: Queue,
|
||||
ctx: CtxSlot,
|
||||
events: Arc<EventLog>,
|
||||
workers: &mut Vec<std::thread::JoinHandle<()>>,
|
||||
budget: &Arc<AtomicUsize>,
|
||||
workers: &mut Vec<Worker>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
workers.retain(|worker| !worker.is_finished());
|
||||
workers.retain(|worker| !worker.thread.is_finished());
|
||||
if workers.len() >= MAX_CONNECTIONS {
|
||||
return;
|
||||
// A client keeping slots it doesn't use can't lock others out (#1110): the connection idle
|
||||
// longest (between requests or in `events.poll`; clients reconnect) gives its slot up. One
|
||||
// whose request the UI is running keeps it.
|
||||
let idle = |w: &Worker| *w.idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let longest = workers.iter().enumerate().filter_map(|(i, w)| Some((i, idle(w)?))).min_by_key(|(_, since)| *since);
|
||||
let Some((i, _)) = longest else { return };
|
||||
let _ = workers.swap_remove(i).stream.shutdown(Shutdown::Both);
|
||||
}
|
||||
let Ok(handle) = stream.try_clone() else { return };
|
||||
let idle: Idle = Arc::new(Mutex::new(Some(Instant::now())));
|
||||
let (budget, mine, token, roots, waiting) = (budget.clone(), idle.clone(), gates.token.clone(), gates.roots.cloned(), gates.waiting.clone());
|
||||
match std::thread::Builder::new().name("figcraft-control-conn".into()).spawn(move || {
|
||||
let _ = serve_with_events(stream, queue, ctx, events, timeout);
|
||||
let close = stream.try_clone();
|
||||
let _ = serve_with_events(stream, Some(&token), roots, Some(&waiting), queue, ctx, events, &budget, &mine, timeout);
|
||||
// The worker keeps a handle on the socket until the next connection reaps it: close it now,
|
||||
// so a connection that ended (a silent one at the token wait) ends for its client too.
|
||||
if let Ok(close) = close {
|
||||
let _ = close.shutdown(Shutdown::Both);
|
||||
}
|
||||
}) {
|
||||
Ok(worker) => workers.push(worker),
|
||||
Ok(thread) => workers.push(Worker { thread, stream: handle, idle }),
|
||||
Err(e) => log::error!("control connection thread: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of a line reserved from the shared budget, given back when dropped.
|
||||
struct Held<'a> {
|
||||
budget: &'a AtomicUsize,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl Drop for Held<'_> {
|
||||
fn drop(&mut self) {
|
||||
self.budget.fetch_sub(self.bytes, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`read_line_by`] read.
|
||||
enum Line<'a> {
|
||||
End,
|
||||
/// A line, its newline included if it had one; longer than [`MAX_LINE`] when it was too long.
|
||||
Read(Held<'a>),
|
||||
/// The connections hold [`MAX_IN_FLIGHT`] bytes already.
|
||||
Busy,
|
||||
}
|
||||
|
||||
/// [`read_line_by`] with no deadline (the tests).
|
||||
#[cfg(test)]
|
||||
fn read_line<'a>(reader: &mut impl BufRead, line: &mut Vec<u8>, budget: &'a AtomicUsize) -> std::io::Result<Line<'a>> {
|
||||
read_line_by(reader, line, budget, None)
|
||||
}
|
||||
|
||||
/// Read a line of at most [`MAX_LINE`] bytes plus its newline into `line`, taking its bytes from
|
||||
/// `budget` as they arrive. With a `deadline` (an instant, and the socket whose read timeout counts
|
||||
/// down to it) it ends then however the line arrives: a client trickling bytes can't stretch it.
|
||||
fn read_line_by<'a>(
|
||||
reader: &mut impl BufRead,
|
||||
line: &mut Vec<u8>,
|
||||
budget: &'a AtomicUsize,
|
||||
deadline: Option<(Instant, &TcpStream)>,
|
||||
) -> std::io::Result<Line<'a>> {
|
||||
let mut held = Held { budget, bytes: 0 };
|
||||
loop {
|
||||
// Data already buffered is returned without a read; the timeout only bounds the next one.
|
||||
if let Some((at, socket)) = deadline {
|
||||
let left = at.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "the token wait ended"));
|
||||
}
|
||||
socket.set_read_timeout(Some(left))?;
|
||||
}
|
||||
let buf = reader.fill_buf()?;
|
||||
if buf.is_empty() {
|
||||
return Ok(if line.is_empty() { Line::End } else { Line::Read(held) });
|
||||
}
|
||||
let room = MAX_LINE + 1 - line.len();
|
||||
let (take, done) = match buf.iter().position(|b| *b == b'\n') {
|
||||
Some(i) if i < room => (i + 1, true),
|
||||
_ => (buf.len().min(room), false),
|
||||
};
|
||||
if budget.try_update(Ordering::SeqCst, Ordering::SeqCst, |used| used.checked_add(take).filter(|t| *t <= MAX_IN_FLIGHT)).is_err() {
|
||||
return Ok(Line::Busy);
|
||||
}
|
||||
held.bytes += take;
|
||||
line.extend_from_slice(&buf[..take]);
|
||||
reader.consume(take);
|
||||
if done || line.len() > MAX_LINE {
|
||||
return Ok(Line::Read(held));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serve one control connection: read bounded JSON lines, reject oversized frames and a
|
||||
/// full queue, queue one request, wait under its gate, and write one reply. Non-JSON input
|
||||
/// answers with an error and closes the connection so HTTP body lines cannot become commands.
|
||||
/// Serve a connection with a private event log (the tests; the app shares its session's log).
|
||||
/// Serve a connection that has shown its token already, with a private event log (the tests; the
|
||||
/// app shares its session's log).
|
||||
#[cfg(test)]
|
||||
fn serve(out: TcpStream, queue: Queue, ctx: CtxSlot, timeout: Duration) -> std::io::Result<()> {
|
||||
serve_with_events(out, queue, ctx, Arc::new(EventLog::default()), timeout)
|
||||
serve_with_events(out, None, None, None, queue, ctx, Arc::new(EventLog::default()), &AtomicUsize::new(0), &Mutex::new(None), timeout)
|
||||
}
|
||||
|
||||
fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc<EventLog>, timeout: Duration) -> std::io::Result<()> {
|
||||
out.set_read_timeout(Some(timeout))?;
|
||||
/// [`serve`] for a connection that must show `token` with its first line.
|
||||
#[cfg(test)]
|
||||
fn serve_with_token(out: TcpStream, token: &str, queue: Queue, ctx: CtxSlot, timeout: Duration) -> std::io::Result<()> {
|
||||
serve_with_events(out, Some(token), None, None, queue, ctx, Arc::new(EventLog::default()), &AtomicUsize::new(0), &Mutex::new(None), timeout)
|
||||
}
|
||||
|
||||
/// `token`: what the first line must carry; `None` only for a connection the tests treat as
|
||||
/// having shown it. `roots`: what every request is confined to. `waiting`: where queued requests'
|
||||
/// gates are noted, for [`Running::stop`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn serve_with_events(
|
||||
mut out: TcpStream,
|
||||
token: Option<&str>,
|
||||
roots: Option<Arc<Roots>>,
|
||||
waiting: Option<&Waiting>,
|
||||
queue: Queue,
|
||||
ctx: CtxSlot,
|
||||
events: Arc<EventLog>,
|
||||
budget: &AtomicUsize,
|
||||
idle: &Mutex<Option<Instant>>,
|
||||
timeout: Duration,
|
||||
) -> std::io::Result<()> {
|
||||
let mut shown = token.is_none();
|
||||
// The token wait is one deadline for the whole first line, however it arrives.
|
||||
let token_by = Instant::now() + timeout.min(TOKEN_WAIT);
|
||||
out.set_read_timeout(Some(if shown { timeout } else { timeout.min(TOKEN_WAIT) }))?;
|
||||
out.set_write_timeout(Some(timeout))?;
|
||||
let mut reader = BufReader::new(out.try_clone()?);
|
||||
let mut line = Vec::new();
|
||||
let set_idle = |since: Option<Instant>| *idle.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = since;
|
||||
loop {
|
||||
line.clear();
|
||||
if (&mut reader).take((MAX_LINE + 1) as u64).read_until(b'\n', &mut line)? == 0 {
|
||||
break;
|
||||
}
|
||||
set_idle(Some(Instant::now()));
|
||||
// A new buffer each time: an idle connection keeps no large line's capacity.
|
||||
let mut line = Vec::new();
|
||||
let deadline = (!shown).then_some((token_by, &out));
|
||||
let _held = match read_line_by(&mut reader, &mut line, budget, deadline)? {
|
||||
Line::End => break,
|
||||
Line::Read(held) => held,
|
||||
Line::Busy => {
|
||||
let error = "the control server holds too many large requests: retry when they are answered";
|
||||
writeln!(out, "{}", json!({"id": null, "ok": false, "error": error}))?;
|
||||
break;
|
||||
}
|
||||
};
|
||||
if line.last() == Some(&b'\n') {
|
||||
line.pop();
|
||||
}
|
||||
@@ -177,11 +396,27 @@ fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc
|
||||
}
|
||||
let Ok(line) = std::str::from_utf8(&line) else { break };
|
||||
if line.trim().is_empty() {
|
||||
// Blank lines can't hold a connection open past the token wait.
|
||||
if !shown {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let reply = match serde_json::from_str::<Value>(line) {
|
||||
Ok(v) => {
|
||||
let id = v.get("id").cloned().unwrap_or(Value::Null);
|
||||
if !shown {
|
||||
let carries =
|
||||
v.get("token").and_then(Value::as_str).zip(token).is_some_and(|(given, want)| craft_control::auth::tokens_match(given, want));
|
||||
if !carries {
|
||||
// Nothing is queued before the token: refused, and the connection ends.
|
||||
let error = "this FigCraft control channel needs its token: send `\"token\"` with the first request, read from the token file the app wrote (docs/control-protocol.md)";
|
||||
writeln!(out, "{}", json!({"id": id, "ok": false, "error": error}))?;
|
||||
break;
|
||||
}
|
||||
shown = true;
|
||||
out.set_read_timeout(Some(timeout))?;
|
||||
}
|
||||
let method = v.get("method").and_then(Value::as_str).unwrap_or("").to_string();
|
||||
let params = v.get("params").cloned().unwrap_or(json!({}));
|
||||
// A poll waits on the shared log, not on a frame: it needs no UI thread and no
|
||||
@@ -205,7 +440,19 @@ fn serve_with_events(mut out: TcpStream, queue: Queue, ctx: CtxSlot, events: Arc
|
||||
continue;
|
||||
}
|
||||
let needs_frame = matches!(method.as_str(), "ui.screenshot" | "ui.input");
|
||||
pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, state: gate.clone() });
|
||||
if let Some(waiting) = waiting {
|
||||
let mut waiting = waiting.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if waiting.closed {
|
||||
drop(waiting);
|
||||
drop(pending);
|
||||
writeln!(out, "{}", json!({"id": id, "ok": false, "error": "the control server has stopped"}))?;
|
||||
break;
|
||||
}
|
||||
waiting.gates.retain(|g| g.state() == RequestState::Open);
|
||||
waiting.gates.push(gate.clone());
|
||||
}
|
||||
set_idle(None);
|
||||
pending.push(ControlRequest { id: id.clone(), method, params, reply: tx, state: gate.clone(), roots: roots.clone() });
|
||||
drop(pending);
|
||||
if let Some(c) = ctx.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {
|
||||
c.request_repaint();
|
||||
|
||||
@@ -30,7 +30,7 @@ fn reply(reader: &mut BufReader<TcpStream>) -> Value {
|
||||
|
||||
/// Build a `ui.inspect` control request with a throwaway reply channel.
|
||||
fn request() -> ControlRequest {
|
||||
ControlRequest { id: json!(0), method: "ui.inspect".into(), params: json!({}), reply: mpsc::channel().0, state: Default::default() }
|
||||
ControlRequest { roots: None, id: json!(0), method: "ui.inspect".into(), params: json!({}), reply: mpsc::channel().0, state: Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -277,46 +277,63 @@ fn a_failed_accept_waits_before_the_next() {
|
||||
assert_eq!(waits, 3, "one wait per failed accept");
|
||||
}
|
||||
|
||||
/// With every slot taken, a new client gets the slot of the connection idle longest, never one
|
||||
/// whose request the UI is running (#1110), and finished slots are reused.
|
||||
#[test]
|
||||
fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() {
|
||||
fn connection_limit_frees_the_longest_idle_slot_and_reuses_finished_ones() {
|
||||
let pending = queue();
|
||||
let ctx = context();
|
||||
let budget = Arc::new(AtomicUsize::new(0));
|
||||
let mut workers = Vec::new();
|
||||
let mut clients = Vec::new();
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
let (client, server) = pair();
|
||||
let spawn = |server, workers: &mut Vec<Worker>| {
|
||||
let events = Arc::new(figcraft_engine::events::EventLog::default());
|
||||
spawn_connection(
|
||||
server,
|
||||
Gates { token: &Arc::from("t"), roots: None, waiting: &Waiting::default() },
|
||||
pending.clone(),
|
||||
ctx.clone(),
|
||||
Arc::new(figcraft_engine::events::EventLog::default()),
|
||||
&mut workers,
|
||||
events,
|
||||
&budget,
|
||||
workers,
|
||||
Duration::from_secs(5),
|
||||
);
|
||||
};
|
||||
for _ in 0..MAX_CONNECTIONS {
|
||||
let (client, server) = pair();
|
||||
spawn(server, &mut workers);
|
||||
clients.push(client);
|
||||
// Each idle from its own moment.
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
assert_eq!(workers.len(), MAX_CONNECTIONS);
|
||||
let (mut extra, server) = pair();
|
||||
spawn_connection(
|
||||
server,
|
||||
pending.clone(),
|
||||
ctx.clone(),
|
||||
Arc::new(figcraft_engine::events::EventLog::default()),
|
||||
&mut workers,
|
||||
Duration::from_secs(5),
|
||||
);
|
||||
assert_eq!(extra.read(&mut [0]).unwrap(), 0);
|
||||
assert_eq!(workers.len(), MAX_CONNECTIONS);
|
||||
for client in clients {
|
||||
client.shutdown(Shutdown::Both).unwrap();
|
||||
}
|
||||
// The oldest connection waits for the UI: it is busy, not idle.
|
||||
clients[0].write_all(b"{\"id\":1,\"method\":\"ui.inspect\",\"token\":\"t\"}\n").unwrap();
|
||||
let start = Instant::now();
|
||||
while workers.iter().any(|worker| !worker.is_finished()) {
|
||||
while pending.lock().unwrap().is_empty() {
|
||||
assert!(start.elapsed() < Duration::from_secs(5));
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
let (mut extra, server) = pair();
|
||||
spawn(server, &mut workers);
|
||||
assert_eq!(workers.len(), MAX_CONNECTIONS);
|
||||
assert_eq!(clients[1].read(&mut [0]).unwrap(), 0, "the connection idle longest was closed");
|
||||
extra.write_all(b"invalid\n").unwrap();
|
||||
assert_eq!(reply(&mut BufReader::new(extra.try_clone().unwrap()))["ok"], false, "the new client is served");
|
||||
assert!(pending.lock().unwrap().len() == 1, "the busy request is still queued");
|
||||
pending.lock().unwrap().clear();
|
||||
for client in clients.iter().skip(2) {
|
||||
client.shutdown(Shutdown::Both).unwrap();
|
||||
}
|
||||
let _ = clients[0].shutdown(Shutdown::Both);
|
||||
// The busy worker waits out its request's 5 s timeout before it sees the shutdown.
|
||||
let start = Instant::now();
|
||||
while workers.iter().any(|worker| !worker.thread.is_finished()) {
|
||||
assert!(start.elapsed() < Duration::from_secs(15));
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let (mut client, server) = pair();
|
||||
spawn_connection(server, pending, ctx, Arc::new(figcraft_engine::events::EventLog::default()), &mut workers, Duration::from_secs(5));
|
||||
spawn(server, &mut workers);
|
||||
assert_eq!(workers.len(), 1);
|
||||
client.write_all(b"invalid\n").unwrap();
|
||||
assert_eq!(reply(&mut BufReader::new(client.try_clone().unwrap()))["ok"], false);
|
||||
@@ -325,7 +342,26 @@ fn connection_limit_rejects_excess_clients_and_reuses_finished_slots() {
|
||||
// returns Ok. Closing the client is what the worker is waiting for, so the result is moot:
|
||||
// the other shutdowns in this file run while the peer is still open and stay checked.
|
||||
let _ = client.shutdown(Shutdown::Both);
|
||||
workers.pop().unwrap().join().unwrap();
|
||||
workers.pop().unwrap().thread.join().unwrap();
|
||||
}
|
||||
|
||||
/// Lines are counted against one budget shared by every connection while they are held (#1111):
|
||||
/// a line past it is refused before it is read whole, and a line answered gives its bytes back.
|
||||
#[test]
|
||||
fn lines_past_the_shared_budget_are_refused_and_given_back_when_done() {
|
||||
let frame = b"{\"id\":1,\"method\":\"ui.inspect\"}\n".to_vec();
|
||||
let nearly_full = AtomicUsize::new(MAX_IN_FLIGHT - 4);
|
||||
let mut line = Vec::new();
|
||||
assert!(matches!(read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &nearly_full).unwrap(), Line::Busy));
|
||||
assert_eq!(nearly_full.load(Ordering::SeqCst), MAX_IN_FLIGHT - 4, "nothing kept from the refused line");
|
||||
let budget = AtomicUsize::new(0);
|
||||
let mut line = Vec::new();
|
||||
{
|
||||
let Line::Read(_held) = read_line(&mut std::io::Cursor::new(frame.clone()), &mut line, &budget).unwrap() else { panic!("read") };
|
||||
assert_eq!(line, frame);
|
||||
assert!(budget.load(Ordering::SeqCst) >= frame.len(), "held while it is served");
|
||||
}
|
||||
assert_eq!(budget.load(Ordering::SeqCst), 0, "given back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -358,7 +394,9 @@ fn events_poll_is_answered_without_the_ui_queue() {
|
||||
let log = Arc::new(figcraft_engine::events::EventLog::default());
|
||||
log.push("comment.added", "Doc", None, json!({"commentId": 7}));
|
||||
let l = log.clone();
|
||||
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
|
||||
let worker = std::thread::spawn(move || {
|
||||
serve_with_events(server, None, None, None, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))
|
||||
});
|
||||
client.write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":0,\"timeoutMs\":0}}\n").unwrap();
|
||||
let mut reader = BufReader::new(client);
|
||||
let r = reply(&mut reader);
|
||||
@@ -484,7 +522,9 @@ fn events_poll_rejects_an_unknown_topic_without_the_ui_queue() {
|
||||
let q = pending.clone();
|
||||
let log = Arc::new(figcraft_engine::events::EventLog::default());
|
||||
let l = log.clone();
|
||||
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
|
||||
let worker = std::thread::spawn(move || {
|
||||
serve_with_events(server, None, None, None, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))
|
||||
});
|
||||
let mut reader = BufReader::new(client);
|
||||
reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"topics\":[\"nope\"],\"timeoutMs\":0}}\n").unwrap();
|
||||
let r = reply(&mut reader);
|
||||
@@ -503,7 +543,9 @@ fn events_poll_reports_reset_for_a_cursor_ahead_of_the_log() {
|
||||
log.push("comment.added", "Doc", None, json!({"commentId": 1}));
|
||||
let q = queue();
|
||||
let l = log.clone();
|
||||
let worker = std::thread::spawn(move || serve_with_events(server, q, context(), l, Duration::from_secs(5)));
|
||||
let worker = std::thread::spawn(move || {
|
||||
serve_with_events(server, None, None, None, q, context(), l, &AtomicUsize::new(0), &Mutex::new(None), Duration::from_secs(5))
|
||||
});
|
||||
let mut reader = BufReader::new(client);
|
||||
reader.get_mut().write_all(b"{\"id\":1,\"method\":\"events.poll\",\"params\":{\"after\":2,\"timeoutMs\":0}}\n").unwrap();
|
||||
let r = reply(&mut reader);
|
||||
@@ -513,3 +555,192 @@ fn events_poll_reports_reset_for_a_cursor_ahead_of_the_log() {
|
||||
reader.get_ref().shutdown(Shutdown::Write).unwrap();
|
||||
worker.join().unwrap().unwrap();
|
||||
}
|
||||
|
||||
/// Serve one connection that must show `token`, send `lines`, and return the replies until the
|
||||
/// server closes it, with what was queued.
|
||||
fn with_token(token: &str, lines: &[&str]) -> (Vec<Value>, usize) {
|
||||
let (client, server) = pair();
|
||||
let q = queue();
|
||||
let (q2, token) = (q.clone(), token.to_string());
|
||||
let worker = std::thread::spawn(move || serve_with_token(server, &token, q2, context(), Duration::from_millis(200)));
|
||||
let mut writer = client.try_clone().unwrap();
|
||||
for line in lines {
|
||||
// The server may have closed already (that's what some of these test).
|
||||
let _ = writeln!(writer, "{line}");
|
||||
}
|
||||
let mut reader = BufReader::new(client);
|
||||
let mut replies = Vec::new();
|
||||
let mut line = String::new();
|
||||
while reader.read_line(&mut line).unwrap_or(0) > 0 {
|
||||
replies.push(serde_json::from_str(&line).unwrap());
|
||||
line.clear();
|
||||
}
|
||||
// A connection let in ends at its idle timeout, which `serve` reports as an error.
|
||||
let _ = worker.join().unwrap();
|
||||
let queued = q.lock().unwrap().len();
|
||||
(replies, queued)
|
||||
}
|
||||
|
||||
// #480: a first request without the token, or with another one, is refused, nothing is queued, and
|
||||
// the connection ends.
|
||||
#[test]
|
||||
fn a_connection_without_its_token_is_refused_before_anything_is_queued() {
|
||||
for first in
|
||||
[r#"{"id":1,"method":"ui.inspect"}"#, r#"{"id":1,"method":"ui.inspect","token":"other"}"#, r#"{"id":1,"method":"events.poll","token":7}"#]
|
||||
{
|
||||
let (replies, queued) = with_token("secret-token", &[first]);
|
||||
assert_eq!(replies.len(), 1, "{first}: one refusal, then the connection ends: {replies:?}");
|
||||
assert_eq!(replies[0]["ok"], json!(false));
|
||||
assert_eq!(replies[0]["id"], json!(1));
|
||||
assert!(replies[0]["error"].as_str().unwrap().contains("token"), "{replies:?}");
|
||||
assert_eq!(queued, 0, "{first}: nothing queued");
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing sent after a refused first request runs, even with the token. (Its replies aren't
|
||||
// checked: closing with a line unread resets the connection on Windows, losing the refusal.)
|
||||
#[test]
|
||||
fn nothing_after_a_refused_first_request_runs() {
|
||||
let (_, queued) = with_token("secret-token", &[r#"{"id":1,"method":"ui.inspect"}"#, r#"{"id":2,"method":"ui.inspect","token":"secret-token"}"#]);
|
||||
assert_eq!(queued, 0);
|
||||
}
|
||||
|
||||
// Blank lines don't hold a connection that hasn't shown its token.
|
||||
#[test]
|
||||
fn a_blank_line_before_the_token_ends_the_connection() {
|
||||
let (replies, queued) = with_token("secret-token", &["", r#"{"id":2,"method":"ui.inspect","token":"secret-token"}"#]);
|
||||
assert!(replies.is_empty(), "{replies:?}");
|
||||
assert_eq!(queued, 0);
|
||||
}
|
||||
|
||||
// The right token lets the first request and the ones after it through.
|
||||
#[test]
|
||||
fn the_token_lets_the_connection_in() {
|
||||
let (replies, _) = with_token("secret-token", &[r#"{"id":1,"method":"ui.inspect","token":"secret-token"}"#, r#"{"id":2,"method":"ui.inspect"}"#]);
|
||||
// No window answers here: both were queued and timed out waiting for it, none was refused.
|
||||
assert_eq!(replies.len(), 2, "{replies:?}");
|
||||
for reply in &replies {
|
||||
assert!(reply["error"].as_str().unwrap().contains("before the app started this request"), "{replies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// A connection that never shows its token gives its slot back after the token wait.
|
||||
#[test]
|
||||
fn a_silent_connection_ends_at_the_token_wait() {
|
||||
let (client, server) = pair();
|
||||
let started = Instant::now();
|
||||
let worker = std::thread::spawn(move || serve_with_token(server, "secret-token", queue(), context(), Duration::from_secs(60)));
|
||||
let _ = worker.join().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(30), "ended at the token wait, not the 60 s request timeout");
|
||||
// Windows may end a read timeout a timer tick early.
|
||||
assert!(started.elapsed() >= TOKEN_WAIT / 2, "waited for the token");
|
||||
drop(client);
|
||||
}
|
||||
|
||||
// The server's own connection closes at the token wait too, though no other connection arrives to
|
||||
// reap its worker: the client sees the end.
|
||||
#[test]
|
||||
fn a_silent_client_is_disconnected_at_the_token_wait() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let running = serve_listener(listener, "secret-token".into(), None, queue(), context(), Arc::new(EventLog::default())).unwrap();
|
||||
let mut client = TcpStream::connect(std::net::SocketAddr::from(([127, 0, 0, 1], running.port()))).unwrap();
|
||||
client.set_read_timeout(Some(Duration::from_secs(20))).unwrap();
|
||||
let started = Instant::now();
|
||||
let read = client.read(&mut [0u8; 16]);
|
||||
assert!(matches!(read, Ok(0)) || read.as_ref().is_err_and(|e| e.kind() == std::io::ErrorKind::ConnectionReset), "{read:?}");
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "closed at the token wait, not held open");
|
||||
running.stop();
|
||||
}
|
||||
|
||||
// Stopping the server closes its listener: nothing connects afterwards.
|
||||
#[test]
|
||||
fn a_stopped_server_accepts_nothing() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let running = serve_listener(listener, "secret-token".into(), None, queue(), context(), Arc::new(EventLog::default())).unwrap();
|
||||
let addr = std::net::SocketAddr::from(([127, 0, 0, 1], running.port()));
|
||||
assert!(TcpStream::connect_timeout(&addr, Duration::from_secs(1)).is_ok());
|
||||
running.stop();
|
||||
// Probing the port again could reach another test's listener that got the same number.
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while !running.ended().load(Ordering::SeqCst) {
|
||||
assert!(Instant::now() < until, "still accepting after stop");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
// A request still queued when the server stops is cancelled: it never runs after the stop (the
|
||||
// launcher's switch turned off), and the UI drops it.
|
||||
#[test]
|
||||
fn stopping_cancels_the_requests_still_queued() {
|
||||
let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
let q = queue();
|
||||
let running = serve_listener(listener, "secret-token".into(), None, q.clone(), context(), Arc::new(EventLog::default())).unwrap();
|
||||
let mut client = TcpStream::connect(("127.0.0.1", running.port())).unwrap();
|
||||
writeln!(client, r#"{{"id":1,"method":"ui.inspect","token":"secret-token"}}"#).unwrap();
|
||||
let until = Instant::now() + Duration::from_secs(5);
|
||||
while q.lock().unwrap().is_empty() {
|
||||
assert!(Instant::now() < until, "the request was never queued");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
running.stop();
|
||||
assert!(q.lock().unwrap()[0].is_cancelled(), "a queued request is cancelled by the stop");
|
||||
let mut ui = Vec::new();
|
||||
drain_queue(&q, &mut ui);
|
||||
assert!(ui.is_empty(), "the UI never sees it");
|
||||
}
|
||||
|
||||
// A connection that queues after the stop closed the registry is refused, and nothing is queued
|
||||
// (the stop and the queueing take the same lock).
|
||||
#[test]
|
||||
fn nothing_is_queued_once_the_server_has_stopped() {
|
||||
let (mut client, server) = pair();
|
||||
let q = queue();
|
||||
let waiting: Waiting = Arc::default();
|
||||
waiting.lock().unwrap().closed = true;
|
||||
let (q2, w2) = (q.clone(), waiting.clone());
|
||||
let worker = std::thread::spawn(move || {
|
||||
serve_with_events(
|
||||
server,
|
||||
None,
|
||||
None,
|
||||
Some(&w2),
|
||||
q2,
|
||||
context(),
|
||||
Arc::new(EventLog::default()),
|
||||
&AtomicUsize::new(0),
|
||||
&Mutex::new(None),
|
||||
Duration::from_secs(5),
|
||||
)
|
||||
});
|
||||
writeln!(client, r#"{{"id":1,"method":"ui.inspect"}}"#).unwrap();
|
||||
let mut reader = BufReader::new(client);
|
||||
let refused = reply(&mut reader);
|
||||
assert_eq!(refused["ok"], json!(false));
|
||||
assert!(refused["error"].as_str().unwrap().contains("stopped"), "{refused}");
|
||||
worker.join().unwrap().unwrap();
|
||||
assert!(q.lock().unwrap().is_empty(), "nothing queued after the stop");
|
||||
assert!(waiting.lock().unwrap().gates.is_empty());
|
||||
}
|
||||
|
||||
// The token wait is one deadline for the whole first line: a client sending a byte at a time,
|
||||
// never a newline, can't hold its connection open past it.
|
||||
#[test]
|
||||
fn a_trickled_first_line_ends_at_the_token_wait() {
|
||||
let (client, server) = pair();
|
||||
let started = Instant::now();
|
||||
let worker = std::thread::spawn(move || serve_with_token(server, "secret-token", queue(), context(), Duration::from_secs(60)));
|
||||
let mut writer = client.try_clone().unwrap();
|
||||
let trickle = std::thread::spawn(move || {
|
||||
for _ in 0..40 {
|
||||
if writer.write_all(b"{").is_err() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
});
|
||||
let _ = worker.join().unwrap();
|
||||
let took = started.elapsed();
|
||||
assert!(took < TOKEN_WAIT * 4, "ended near the token wait ({TOKEN_WAIT:?}), not after the trickle: {took:?}");
|
||||
drop(client);
|
||||
let _ = trickle.join();
|
||||
}
|
||||
@@ -4,7 +4,15 @@
|
||||
//! first, on Windows too. A Vulkan driver that faults there takes the app down as the window opens:
|
||||
//! an access violation inside the vendor's driver, which no guard of ours can catch (seen on a laptop
|
||||
//! with two AMD GPUs whose drivers were years apart). Direct3D 12 is part of Windows, so on Windows
|
||||
//! wgpu is offered Direct3D 12, and OpenGL for hardware without a Direct3D 12 driver.
|
||||
//! wgpu is offered Direct3D 12 alone at first.
|
||||
//!
|
||||
//! Not OpenGL beside it: wgpu's OpenGL backend on Windows makes a hidden window on a thread of its
|
||||
//! own that handles no window messages, as soon as the instance is created, whichever backend then
|
||||
//! draws. Windows hands an input language change (Alt+Shift or Win+Space to a Russian layout,
|
||||
//! #2264) to every thread of the app with a window, so the main window waited on that hidden one
|
||||
//! and the app hung. Direct3D 12 always lists its software adapter (WARP), so a GPU with no
|
||||
//! Direct3D 12 driver (Intel Haswell, which wgpu leaves out of Direct3D 12, and older ones) now
|
||||
//! draws on WARP rather than on its OpenGL driver.
|
||||
//!
|
||||
//! Two shader compilers lost the device before the window opened ("Parent device is lost", #965,
|
||||
//! #1438), both on wgpu's indirect-call validation shaders, which wgpu compiles with every device:
|
||||
@@ -14,10 +22,12 @@
|
||||
//! out: FigCraft draws nothing indirectly, so they would check nothing.
|
||||
//!
|
||||
//! When the graphics still fail before the window's first frame, the app starts again with the
|
||||
//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; and last the first
|
||||
//! next of its [`attempts`]: on Windows Vulkan, then OpenGL; elsewhere OpenGL; then the first
|
||||
//! backends again with lower requirements on the power-saving GPU (macOS has no OpenGL in wgpu, so
|
||||
//! that is its only other try). The attempts are a fixed list, so this ends; the message the last
|
||||
//! one shows names what was tried.
|
||||
//! that is its only other try); and on Windows last OpenGL with lower requirements, each on its own
|
||||
//! so that OpenGL starts only when Direct3D 12 failed. An OpenGL start on Windows can still hang on
|
||||
//! an input language change. The attempts are a fixed list, so this ends; the message the last one
|
||||
//! shows names what was tried.
|
||||
//!
|
||||
//! `WGPU_BACKEND` (`dx12`, `vulkan`, `gl`, `metal`) still names the backend on every system, and
|
||||
//! is then the one attempt. `WGPU_DX12_COMPILER` and `WGPU_VALIDATION_INDIRECT_CALL` still choose
|
||||
@@ -36,8 +46,9 @@ pub const ATTEMPT_ENV: &str = "FIGCRAFT_GRAPHICS_ATTEMPT";
|
||||
/// begins once the first was presented.
|
||||
pub const STARTUP_FRAMES: u64 = 2;
|
||||
|
||||
/// Direct3D 12, then OpenGL: wgpu ranks a hardware GPU on either ahead of Direct3D's software one.
|
||||
const WINDOWS: Backends = Backends::DX12.union(Backends::GL);
|
||||
/// Direct3D 12 alone: an OpenGL instance beside it hangs the window on an input language change
|
||||
/// (see the module docs).
|
||||
const WINDOWS: Backends = Backends::DX12;
|
||||
|
||||
/// The graphics APIs by name, in the order the startup message lists them.
|
||||
const NAMES: [(Backends, &str); 4] =
|
||||
@@ -54,7 +65,8 @@ pub struct Attempt {
|
||||
|
||||
/// The ways to start, in order: only `WGPU_BACKEND`'s backends (`requested`) when it is set;
|
||||
/// otherwise [`WINDOWS`] on Windows, else eframe's `defaults`, then Vulkan on Windows, OpenGL
|
||||
/// except on macOS, and those first backends again with lower requirements.
|
||||
/// except on macOS, those first backends again with lower requirements, and on Windows OpenGL with
|
||||
/// lower requirements.
|
||||
pub fn attempts(requested: Option<Backends>, windows: bool, macos: bool, defaults: Backends) -> Vec<Attempt> {
|
||||
let normal = |backends| Attempt { backends, lower: false };
|
||||
if let Some(requested) = requested {
|
||||
@@ -69,6 +81,9 @@ pub fn attempts(requested: Option<Backends>, windows: bool, macos: bool, default
|
||||
list.push(normal(Backends::GL));
|
||||
}
|
||||
list.push(Attempt { backends: first, lower: true });
|
||||
if windows {
|
||||
list.push(Attempt { backends: Backends::GL, lower: true });
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The graphics attempts: no Vulkan on Windows at first (a faulting Vulkan driver crashed the app
|
||||
//! as its window opened), another backend and then lower requirements when the graphics fail
|
||||
//! before the first frame (#965, #1438), and never more starts than attempts.
|
||||
//! as its window opened), never OpenGL beside Direct3D 12 there (its hidden window hung the app on
|
||||
//! an input language change, #2264), another backend and then lower requirements when the graphics
|
||||
//! fail before the first frame (#965, #1438), and never more starts than attempts.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -13,8 +14,6 @@ use crate::graphics::{ATTEMPT_ENV, Attempt, Plan, STARTUP_FRAMES, apply, attempt
|
||||
/// What eframe offers when `WGPU_BACKEND` isn't set.
|
||||
const DEFAULTS: Backends = Backends::PRIMARY.union(Backends::GL);
|
||||
|
||||
const DX12_GL: Backends = Backends::DX12.union(Backends::GL);
|
||||
|
||||
const fn normal(backends: Backends) -> Attempt {
|
||||
Attempt { backends, lower: false }
|
||||
}
|
||||
@@ -26,10 +25,21 @@ const fn lower(backends: Backends) -> Attempt {
|
||||
#[test]
|
||||
fn windows_starts_on_direct3d_then_vulkan_then_opengl_then_lower_requirements() {
|
||||
let list = attempts(None, true, false, DEFAULTS);
|
||||
assert_eq!(list, [normal(DX12_GL), normal(Backends::VULKAN), normal(Backends::GL), lower(DX12_GL)]);
|
||||
assert_eq!(list, [normal(Backends::DX12), normal(Backends::VULKAN), normal(Backends::GL), lower(Backends::DX12), lower(Backends::GL)]);
|
||||
assert!(!list[0].backends.contains(Backends::VULKAN), "a Vulkan driver that faults can't be picked at first");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_never_starts_opengl_beside_direct3d_but_still_falls_back_to_it() {
|
||||
let list = attempts(None, true, false, DEFAULTS);
|
||||
for attempt in &list {
|
||||
assert!(!attempt.backends.contains(Backends::DX12 | Backends::GL), "OpenGL's hidden window hangs a Direct3D 12 start: {attempt:?}");
|
||||
}
|
||||
assert!(list.iter().any(|a| a.backends.contains(Backends::VULKAN)), "Vulkan is still tried");
|
||||
assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && !a.lower), "OpenGL is still tried");
|
||||
assert!(list.iter().any(|a| a.backends.contains(Backends::GL) && a.lower), "and with lower requirements");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_falls_back_to_opengl_then_lower_requirements() {
|
||||
assert_eq!(attempts(None, false, false, DEFAULTS), [normal(DEFAULTS), normal(Backends::GL), lower(DEFAULTS)]);
|
||||
|
||||
+48
-16
@@ -20,6 +20,7 @@
|
||||
#[cfg(all(target_os = "windows", target_env = "gnu", not(windows_slim_errors)))]
|
||||
compile_error!("Windows GNU builds must set windows_slim_errors to keep UI Automation responsive");
|
||||
|
||||
mod agents;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod apple_events;
|
||||
mod args;
|
||||
@@ -86,6 +87,9 @@ struct App {
|
||||
/// earlier session's record stays for the next start to report (a renderer failure before the
|
||||
/// first frame must not acknowledge it).
|
||||
nightly_notice_pending: bool,
|
||||
/// The ArtCraft Launcher's agents switch and the listener it turns on and off (#2740); `None`
|
||||
/// in a Nightly, which never opens the control channel, or with no settings folder.
|
||||
agents: Option<agents::Agents>,
|
||||
}
|
||||
|
||||
impl eframe::App for App {
|
||||
@@ -100,6 +104,12 @@ impl eframe::App for App {
|
||||
}
|
||||
}
|
||||
let title = with_app(|fig| {
|
||||
if let Some(agents) = self.agents.as_mut() {
|
||||
let (queue, slot, events) = (&self.queue, &self.ctx_slot, &fig.session.events);
|
||||
agents.tick(&mut |listener, token, roots| {
|
||||
control_server::serve_listener(listener, token, roots, queue.clone(), slot.clone(), events.clone())
|
||||
});
|
||||
}
|
||||
control_server::drain_queue(&self.queue, &mut fig.control_queue);
|
||||
// Phase-safe background work: control queues, autosave/recovery deadlines, live polling.
|
||||
// It runs on logic-only callbacks too, so it never reads UI input.
|
||||
@@ -156,6 +166,10 @@ impl eframe::App for App {
|
||||
}
|
||||
|
||||
fn on_exit(&mut self) {
|
||||
// Agents can't reach a closing app: its connection file goes first.
|
||||
if let Some(agents) = self.agents.as_mut() {
|
||||
agents.stop();
|
||||
}
|
||||
// With the app out of reach (busy), its recovery copies stay for the next start.
|
||||
let copies = recovery::lock(&self.recovery).take();
|
||||
with_app(|fig| {
|
||||
@@ -262,6 +276,12 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
|
||||
Some(early.args)
|
||||
}
|
||||
|
||||
fn open_startup_files(app: &mut FigApp, files: &[String]) {
|
||||
for path in files {
|
||||
app.run_user("file.open", json!({"path": path}));
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
// The launch profile comes before the logger, the update helper, fonts and saved state.
|
||||
let Some(arguments) = prepare_launch() else { return Ok(()) };
|
||||
@@ -352,19 +372,17 @@ fn main() -> eframe::Result {
|
||||
if let Some(prefs) = svc.prefs.clone() {
|
||||
session.prefs = prefs;
|
||||
}
|
||||
// A file that won't open is said in the window too: it may have been double-clicked.
|
||||
let mut failed_open = None;
|
||||
for f in &args.files {
|
||||
if let Err(e) = session.execute("file.open", &json!({"path": f})) {
|
||||
log::error!("{f}: {e}");
|
||||
let name = std::path::Path::new(f).file_name().map_or_else(|| f.into(), |n| n.to_string_lossy());
|
||||
failed_open = Some(format!("{name}: {e}"));
|
||||
}
|
||||
}
|
||||
let first_run = svc.prefs.is_none() && args.join.is_none();
|
||||
// Initialise the interface language before opening files, as startup can now show an import
|
||||
// report or retry prompt just like File > Open.
|
||||
figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref());
|
||||
let mut fig = FigApp::new(session, Box::new(svc));
|
||||
open_startup_files(&mut fig, &args.files);
|
||||
let session = &mut fig.session;
|
||||
let mut opened: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
// Documents a crashed or killed run left unsaved come back; this run keeps its own copies.
|
||||
let recovery_root = services::config_dir().map(|d| d.join("Recovery"));
|
||||
let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, &mut session)).unwrap_or_default();
|
||||
let recovered = recovery_root.as_deref().map(|r| recovery::recover_all(r, session)).unwrap_or_default();
|
||||
let mut copies = recovery_root.as_deref().and_then(recovery::Recovery::start);
|
||||
// Copies of online files stay until their files arrive from their servers.
|
||||
if let Some(r) = copies.as_mut() {
|
||||
@@ -380,7 +398,7 @@ fn main() -> eframe::Result {
|
||||
session.live.links = figcraft_collab_net::links::system();
|
||||
session.invite_links_startup();
|
||||
}
|
||||
let first_run = svc.prefs.is_none() && args.join.is_none();
|
||||
let mut failed_open = None;
|
||||
if reopens_files(first_run, session.prefs.start_on_home) {
|
||||
let before: Vec<u64> = session.docs.iter().map(|d| d.uid).collect();
|
||||
for (path, e) in session.reopen_files() {
|
||||
@@ -397,16 +415,13 @@ fn main() -> eframe::Result {
|
||||
if session.docs.is_empty() && opens_new_file(first_run, port.is_some()) {
|
||||
let _ = session.execute("file.new", &json!({}));
|
||||
}
|
||||
// The interface language from the first frame on, and for the message when the window can't
|
||||
// open (no frame then).
|
||||
figcraft_ui_egui::i18n::set(&session.prefs.language, figcraft_ui_egui::Services::system_language(&svc).as_deref());
|
||||
let mut fig = FigApp::new(session, Box::new(svc));
|
||||
if nightly {
|
||||
// The Launcher keeps the Nightly on the version it installed.
|
||||
fig.disable_updates();
|
||||
} else {
|
||||
fig.set_startup_update_check(true);
|
||||
}
|
||||
let own_roots = roots.is_some();
|
||||
fig.automation_roots = roots;
|
||||
fig.ui.home = false;
|
||||
// Files named on the command line or reopened are the user's too: their missing fonts are
|
||||
@@ -421,7 +436,16 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
let queue: Arc<Mutex<Vec<ControlRequest>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
if let Some(p) = port {
|
||||
control_server::start(p, graphics::port_wait(), queue.clone(), ctx_slot.clone(), fig.session.events.clone());
|
||||
let (q, slot, events) = (queue.clone(), ctx_slot.clone(), fig.session.events.clone());
|
||||
match agents::serve_port(p, graphics::port_wait(), &mut |listener, token, roots| {
|
||||
control_server::serve_listener(listener, token, roots, q.clone(), slot.clone(), events.clone())
|
||||
}) {
|
||||
Ok(_) => eprintln!("FigCraft control server listening on 127.0.0.1:{p}"),
|
||||
Err(e) => {
|
||||
log::error!("control server: {e}");
|
||||
eprintln!("FigCraft control server on port {p}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let icon = services::window_icon();
|
||||
// The app id is the Wayland app_id and the X11 window class on Linux: the desktop entry's name
|
||||
@@ -511,6 +535,14 @@ fn main() -> eframe::Result {
|
||||
nightly: exit_record,
|
||||
nightly_notice: exit_notice,
|
||||
nightly_notice_pending,
|
||||
agents: if nightly {
|
||||
None
|
||||
} else {
|
||||
services::config_dir().map(|dir| {
|
||||
let ctx = cc.egui_ctx.clone();
|
||||
agents::Agents::watch(dir, own_roots, move || ctx.request_repaint())
|
||||
})
|
||||
},
|
||||
// The custom title bar's undecorated window must stay borderless, or its caption
|
||||
// and border offset the content and the pointer on some Windows systems (#1343).
|
||||
window_frame: window_frame::WindowFrame::new(custom_titlebar),
|
||||
|
||||
@@ -168,9 +168,17 @@ fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Res
|
||||
if child == chosen || !child.starts_with(&chosen) {
|
||||
return Err(format!("the nightly {label} must stay inside its selected profile"));
|
||||
}
|
||||
match std::fs::metadata(&child) {
|
||||
Ok(metadata) if !metadata.is_dir() => return Err(format!("the nightly {label} must be a directory")),
|
||||
Ok(_) => {}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
|
||||
}
|
||||
Ok(child)
|
||||
}
|
||||
|
||||
const PROFILE_FOLDERS: [&str; 4] = ["Recovery", "Plugins", "Fonts", "logs"];
|
||||
|
||||
/// Every existing entry directly in the profile (Plugins, logs, settings and so on) must resolve
|
||||
/// inside it, so a link there cannot point Nightly's writes at another app's data.
|
||||
fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
@@ -181,11 +189,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
|
||||
};
|
||||
for entry in entries {
|
||||
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
let path = entry.path();
|
||||
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
|
||||
// Settings and session state are ordinary files, not directories. Keep the existing
|
||||
// directory-boundary check for folders (including the known folder-only entries).
|
||||
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
|
||||
if metadata.is_file() && !folder_only {
|
||||
private_regular_file(&path, &metadata)?;
|
||||
} else {
|
||||
private_subdirectory(root, entry.file_name(), "profile entry")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persisted files must have their own ordinary file identity, not an alias to other data.
|
||||
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
if metadata.nlink() != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use winsafe::{HFILE, co};
|
||||
let (file, _) = HFILE::CreateFile(
|
||||
path.to_str().ok_or("the nightly profile file path is not textual")?,
|
||||
co::GENERIC::default(),
|
||||
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
|
||||
None,
|
||||
co::DISPOSITION::OPEN_EXISTING,
|
||||
co::FILE_ATTRIBUTE::NORMAL,
|
||||
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
|
||||
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
|
||||
return Err("the nightly profile file must not be an alias or directory".into());
|
||||
}
|
||||
if info.nNumberOfLinks != 1 {
|
||||
return Err("the nightly profile file must not be shared".into());
|
||||
}
|
||||
}
|
||||
let _ = (path, metadata);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A portable FigCraft copy: the marker file beside the executable (or the `.app` on macOS).
|
||||
fn portable_copy(dir: &Path) -> bool {
|
||||
dir.join(PORTABLE_MARKER).is_file() && PORTABLE_EXES.iter().any(|exe| dir.join(exe).exists())
|
||||
@@ -498,6 +551,31 @@ mod tests {
|
||||
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
|
||||
let fixture = Fixture::new();
|
||||
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
|
||||
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
for name in ["state.json", "nightly-session.lock", "nightly-session.json"] {
|
||||
std::fs::write(private.join(name), b"saved profile data").unwrap();
|
||||
}
|
||||
for name in PROFILE_FOLDERS {
|
||||
std::fs::create_dir(private.join(name)).unwrap();
|
||||
}
|
||||
assert_eq!(fixture.check(platform, &private).unwrap(), private);
|
||||
assert_eq!(std::fs::read(private.join("state.json")).unwrap(), b"saved profile data");
|
||||
for name in PROFILE_FOLDERS {
|
||||
let path = private.join(name);
|
||||
std::fs::remove_dir(&path).unwrap();
|
||||
std::fs::write(&path, b"not a directory").unwrap();
|
||||
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
|
||||
let mut fixture = Fixture::new();
|
||||
|
||||
@@ -49,3 +49,26 @@ fn after_every_attempt_failed_it_names_what_was_tried_and_no_other_api() {
|
||||
assert!(!text.contains(tr(DRIVER_HINT)), "every API was tried already: {text}");
|
||||
assert!(text.contains("https://github.com/storytold/figcraft/issues"), "where to report it: {text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_fig_at_startup_shows_the_import_report() {
|
||||
use figcraft_engine::Session;
|
||||
use figcraft_ui_egui::{FigApp, NoServices};
|
||||
use serde_json::json;
|
||||
|
||||
let mut source = Session::new();
|
||||
source.execute("node.create", &json!({"type": "rectangle", "name": "Startup rectangle"})).unwrap();
|
||||
let (bytes, _) = figcraft_engine::cmd::file::fig_bytes(source.doc().unwrap()).unwrap();
|
||||
let path = std::env::temp_dir().join(format!("figcraft-startup-import-{}.fig", std::process::id()));
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
|
||||
let mut app = FigApp::new(Session::empty(), Box::new(NoServices));
|
||||
super::open_startup_files(&mut app, &[path.to_string_lossy().into_owned()]);
|
||||
std::fs::remove_file(path).unwrap();
|
||||
|
||||
let state = app.session.ds().expect("the startup file opened");
|
||||
let report = app.ui.import_report.as_ref().expect("a startup .fig uses the same import report as File > Open");
|
||||
assert_eq!(report.uid, state.uid);
|
||||
assert_eq!(report.layers, Some(1));
|
||||
assert!(state.doc.nodes().any(|node| node.name == "Startup rectangle"));
|
||||
}
|
||||
@@ -141,3 +141,14 @@ real_name = "Ibuchukwu Umeano"
|
||||
|
||||
[people.Terra854]
|
||||
display_name = "Terra854"
|
||||
|
||||
[people.andrejskvorc]
|
||||
real_name = "Andrej Skvorc"
|
||||
|
||||
[people.victorazesc]
|
||||
sync_github_name = true
|
||||
|
||||
[people.brytoncooper]
|
||||
real_name = "Bryton Cooper"
|
||||
display_name = "Bryton Cooper"
|
||||
sync_github_name = true
|
||||
@@ -15,18 +15,22 @@ figcraft-doc = { workspace = true }
|
||||
log = { workspace = true }
|
||||
# `std::time::Instant` natively, the browser's clock in the web build.
|
||||
web-time = "1"
|
||||
# Invite links write a session certificate's SHA-256 (`cert=`) in URL-safe base64.
|
||||
base64 = { workspace = true }
|
||||
|
||||
# Native transport: blocking tungstenite with a reader and a writer thread per connection.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
tungstenite = { version = "0.30", default-features = false, features = ["handshake"] }
|
||||
# `wss://`: TLS with ring as the crypto provider and Mozilla's root certificates compiled in (no
|
||||
# OS certificate store, no OpenSSL). Over our own split reader/writer stream (`tls.rs`), so not
|
||||
# tungstenite's single-owner TLS stream.
|
||||
# `wss://`: TLS with ring as the crypto provider, the public root certificates of webpki-roots
|
||||
# compiled in and the operating system's certificate store read (no OpenSSL). Over our own split
|
||||
# reader/writer stream (`tls.rs`), so not tungstenite's single-owner TLS stream.
|
||||
rustls = { version = "0.23", default-features = false, features = ["std", "ring", "tls12", "logging"] }
|
||||
rustls-pki-types = { version = "1", features = ["std"] }
|
||||
webpki-roots = "1"
|
||||
rustls-native-certs = "0.8"
|
||||
getrandom = "0.4"
|
||||
base64 = { workspace = true }
|
||||
# A hosting app's own Ed25519 certificate (`cert.rs`): the provider rustls already uses.
|
||||
ring = "0.17"
|
||||
|
||||
# The browser client: the page's WebSocket API.
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
//! A session's own certificate (native): a fresh Ed25519 key and a self-signed X.509 v3
|
||||
//! certificate for it, made when an app starts hosting on the network and gone when it stops.
|
||||
//! Nobody vouches for it; the invite link carries its SHA-256 instead (`cert=`), and a guest
|
||||
//! connects only to a host presenting exactly that certificate ([`crate::tls::handshake_pinned`]).
|
||||
//!
|
||||
//! The certificate is written out as DER by hand (a few fixed structures), so hosting needs no
|
||||
//! certificate library: its validity runs from 2000 to 9999-12-31 (RFC 5280's "no expiry"), as
|
||||
//! the pin, not a date, is what's checked.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use ring::rand::{SecureRandom, SystemRandom};
|
||||
use ring::signature::{Ed25519KeyPair, KeyPair};
|
||||
use rustls::ServerConfig;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
|
||||
/// The SHA-256 of a certificate's DER: what an invite pins.
|
||||
pub type Fingerprint = [u8; 32];
|
||||
|
||||
/// A session's certificate, its private key and its fingerprint.
|
||||
pub struct SessionCert {
|
||||
pub cert: CertificateDer<'static>,
|
||||
pub key: PrivateKeyDer<'static>,
|
||||
pub sha256: Fingerprint,
|
||||
}
|
||||
|
||||
/// The SHA-256 of `der`.
|
||||
pub fn fingerprint(der: &[u8]) -> Fingerprint {
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(ring::digest::digest(&ring::digest::SHA256, der).as_ref());
|
||||
out
|
||||
}
|
||||
|
||||
/// `id-Ed25519` (1.3.101.112), as an AlgorithmIdentifier: no parameters (RFC 8410).
|
||||
const ED25519: &[u8] = &[0x30, 0x05, 0x06, 0x03, 0x2B, 0x65, 0x70];
|
||||
|
||||
/// A DER element: `tag`, its length, `body`.
|
||||
fn der(tag: u8, body: &[u8]) -> Vec<u8> {
|
||||
let mut out = vec![tag];
|
||||
match u8::try_from(body.len()) {
|
||||
Ok(n) if n < 0x80 => out.push(n),
|
||||
_ => {
|
||||
// Long form: the length's bytes without leading zeros, after their count.
|
||||
let bytes = body.len().to_be_bytes();
|
||||
let len: Vec<u8> = bytes.iter().copied().skip_while(|b| *b == 0).collect();
|
||||
out.push(0x80 | u8::try_from(len.len()).unwrap_or(0));
|
||||
out.extend_from_slice(&len);
|
||||
}
|
||||
}
|
||||
out.extend_from_slice(body);
|
||||
out
|
||||
}
|
||||
|
||||
fn seq(parts: &[&[u8]]) -> Vec<u8> {
|
||||
der(0x30, &parts.concat())
|
||||
}
|
||||
|
||||
/// A BIT STRING of whole bytes.
|
||||
fn bits(b: &[u8]) -> Vec<u8> {
|
||||
der(0x03, &[&[0u8][..], b].concat())
|
||||
}
|
||||
|
||||
/// `CN=<name>`.
|
||||
fn name(cn: &str) -> Vec<u8> {
|
||||
let attr = seq(&[&der(0x06, &[0x55, 0x04, 0x03]), &der(0x0C, cn.as_bytes())]);
|
||||
seq(&[&der(0x31, &attr)])
|
||||
}
|
||||
|
||||
/// The to-be-signed part of a certificate for `public` (32 bytes) with `serial`.
|
||||
fn tbs(serial: &[u8; 16], public: &[u8]) -> Vec<u8> {
|
||||
let version = der(0xA0, &der(0x02, &[2]));
|
||||
let subject = name("FigCraft live session");
|
||||
let validity = seq(&[&der(0x17, b"000101000000Z"), &der(0x18, b"99991231235959Z")]);
|
||||
let spki = seq(&[ED25519, &bits(public)]);
|
||||
// basicConstraints (2.5.29.19), critical: not an authority.
|
||||
let basic = seq(&[&der(0x06, &[0x55, 0x1D, 0x13]), &der(0x01, &[0xFF]), &der(0x04, &seq(&[]))]);
|
||||
let extensions = der(0xA3, &seq(&[&basic]));
|
||||
seq(&[&version, &der(0x02, serial), ED25519, &subject, &validity, &subject, &spki, &extensions])
|
||||
}
|
||||
|
||||
/// A fresh key and a self-signed certificate for it.
|
||||
pub fn generate() -> Result<SessionCert, String> {
|
||||
let rng = SystemRandom::new();
|
||||
let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).map_err(|_| "can't make a key for the session's certificate")?;
|
||||
let pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).map_err(|_| "can't read the session's new key")?;
|
||||
let mut serial = [0u8; 16];
|
||||
rng.fill(&mut serial).map_err(|_| "no randomness for the session's certificate")?;
|
||||
// A positive INTEGER with no leading zero byte.
|
||||
serial[0] = (serial[0] & 0x7F) | 0x01;
|
||||
let tbs = tbs(&serial, pair.public_key().as_ref());
|
||||
let signature = pair.sign(&tbs);
|
||||
let cert = seq(&[&tbs, ED25519, &bits(signature.as_ref())]);
|
||||
let sha256 = fingerprint(&cert);
|
||||
Ok(SessionCert { cert: CertificateDer::from(cert), key: PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(pkcs8.as_ref().to_vec())), sha256 })
|
||||
}
|
||||
|
||||
/// The server settings presenting `cert`.
|
||||
pub fn server_config(cert: &SessionCert) -> Result<Arc<ServerConfig>, String> {
|
||||
let cfg = ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert.cert.clone()], cert.key.clone_key())
|
||||
.map_err(|e| format!("the session's certificate isn't usable: {e}"))?;
|
||||
Ok(Arc::new(cfg))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn long_lengths_use_the_fewest_bytes() {
|
||||
assert_eq!(der(0x04, &[0; 0x7F])[..2], [0x04, 0x7F]);
|
||||
assert_eq!(der(0x04, &[0; 0x80])[..3], [0x04, 0x81, 0x80]);
|
||||
assert_eq!(der(0x04, &[0; 0x1234])[..4], [0x04, 0x82, 0x12, 0x34]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_certificate_is_new_and_its_fingerprint_is_its_hash() {
|
||||
let (a, b) = (generate().unwrap(), generate().unwrap());
|
||||
assert_ne!(a.sha256, b.sha256);
|
||||
assert_eq!(a.sha256, fingerprint(a.cert.as_ref()));
|
||||
// rustls (webpki) parses it and accepts the key as its own.
|
||||
server_config(&a).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,32 @@ fn a_share_on_every_interface_names_an_address_others_reach() {
|
||||
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
|
||||
}
|
||||
|
||||
/// A session hosted for other machines (here on every interface, without a join code) serves TLS
|
||||
/// with a certificate of its own: its links are `wss://` and pin it, a guest joining with them
|
||||
/// edits along both ways, and the same session as a plain `ws://` link gets nowhere.
|
||||
#[test]
|
||||
fn a_network_host_serves_tls_its_links_pin_and_edits_sync() {
|
||||
let (mut host, mut guest, mut plain) = (session("Hana"), session("Ada"), session("Bo"));
|
||||
let hosted = host.execute("collab.host", &json!({"bind": "0.0.0.0"})).unwrap();
|
||||
let (link, url) = (hosted["link"].as_str().unwrap().to_string(), hosted["url"].as_str().unwrap().to_string());
|
||||
let invite = Invite::parse(&link).unwrap();
|
||||
assert!(invite.server.secure && invite.server.cert.is_some(), "{link}");
|
||||
assert_eq!(Invite::parse(&url).unwrap(), invite, "the link and the URL name the same pin");
|
||||
guest.execute("collab.join", &json!({"link": link})).unwrap();
|
||||
pump(&mut [&mut host, &mut guest], "the join", |s| live(s[1]) && s[0].live().peers.len() == 1);
|
||||
let before = layers(&host);
|
||||
host.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
pump(&mut [&mut host, &mut guest], "the host's edit", |s| layers(s[1]) == before + 1);
|
||||
guest.execute("shape.ellipse", &json!({"x": 80, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
pump(&mut [&mut host, &mut guest], "the guest's edit", |s| layers(s[0]) == before + 2);
|
||||
// Without TLS the host doesn't answer.
|
||||
let unpinned = Invite::new(invite.server.host.clone(), invite.file.clone(), invite.token.clone());
|
||||
plain.execute("collab.join", &json!({"link": unpinned.link()})).unwrap();
|
||||
pump(&mut [&mut host, &mut guest, &mut plain], "the plain join's failure", |s| matches!(s[2].live().status, Status::Failed { .. }));
|
||||
assert_eq!(host.live().peers.len(), 1);
|
||||
assert_eq!(host.execute("collab.stop", &json!({})).unwrap()["ended"], true);
|
||||
}
|
||||
|
||||
/// A listener on one address is reached at it; one on every interface at an address of its own
|
||||
/// family, on its port.
|
||||
#[test]
|
||||
|
||||
@@ -636,6 +636,7 @@ fn joins_a_real_host_and_edits_with_it() {
|
||||
name: "Hana".into(),
|
||||
limits: fast_limits(),
|
||||
core: Limits::default(),
|
||||
tls: false,
|
||||
},
|
||||
host_probe.clone(),
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ use figcraft_engine::live::{Event, PEOPLE};
|
||||
pub use crate::hub::REMOVED;
|
||||
use crate::hub::{Admission, Backend, Closing, Hosting, Local, clean_name, to_local};
|
||||
use crate::inbox::Inbox;
|
||||
use crate::invite::Endpoint;
|
||||
pub use crate::join::ENDED;
|
||||
use crate::net::NetLimits;
|
||||
|
||||
@@ -36,12 +37,17 @@ pub struct HostConfig {
|
||||
pub name: String,
|
||||
pub limits: NetLimits,
|
||||
pub core: figcraft_collab::Limits,
|
||||
/// Serve TLS with a certificate made for this session ([`crate::cert`]): every guest must
|
||||
/// connect over it, to exactly that certificate ([`Host::cert_sha256`] for their links). For
|
||||
/// a host others reach over a network, where the token would otherwise travel in the clear.
|
||||
pub tls: bool,
|
||||
}
|
||||
|
||||
/// A running session host. Dropping it stops it.
|
||||
pub struct Host {
|
||||
hosting: Hosting,
|
||||
me: Peer,
|
||||
cert_sha256: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// The app's one file and its tokens: whoever has the edit token edits, whoever has the view
|
||||
@@ -94,6 +100,14 @@ impl Host {
|
||||
"this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again"
|
||||
)));
|
||||
}
|
||||
// A new certificate each session: an old invite's pin never matches a later session.
|
||||
let (tls, cert_sha256) = match cfg.tls {
|
||||
true => {
|
||||
let cert = crate::cert::generate().map_err(io::Error::other)?;
|
||||
(Some(crate::cert::server_config(&cert).map_err(io::Error::other)?), Some(cert.sha256))
|
||||
}
|
||||
false => (None, None),
|
||||
};
|
||||
let listener = match TcpListener::bind(cfg.addr) {
|
||||
Ok(l) => l,
|
||||
Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?,
|
||||
@@ -127,8 +141,8 @@ impl Host {
|
||||
let me = server.peers().find(|p| p.client_id == me).cloned().ok_or_else(|| io::Error::other("the host didn't join its own session"))?;
|
||||
let backend = OneFile { file: cfg.file.clone(), token: cfg.token, view: cfg.view_token };
|
||||
let local = Local { file: cfg.file, server, id: me.client_id, inbox };
|
||||
let hosting = Hosting::start(listener, backend, cfg.limits, Some(local))?;
|
||||
Ok(Host { hosting, me })
|
||||
let hosting = Hosting::start(listener, backend, cfg.limits, Some(local), tls)?;
|
||||
Ok(Host { hosting, me, cert_sha256 })
|
||||
}
|
||||
|
||||
/// Where it listens.
|
||||
@@ -136,6 +150,20 @@ impl Host {
|
||||
self.hosting.addr()
|
||||
}
|
||||
|
||||
/// The SHA-256 of the certificate it serves TLS with (`None`: plain `ws://`).
|
||||
pub fn cert_sha256(&self) -> Option<[u8; 32]> {
|
||||
self.cert_sha256
|
||||
}
|
||||
|
||||
/// Where others connect to, at `host` (`host:port`): `wss://` to its certificate when it has
|
||||
/// one, else plain `ws://`.
|
||||
pub fn endpoint(&self, host: impl Into<String>) -> Endpoint {
|
||||
match self.cert_sha256 {
|
||||
Some(c) => Endpoint::pinned(host, c),
|
||||
None => Endpoint::plain(host),
|
||||
}
|
||||
}
|
||||
|
||||
/// The host as the others see them.
|
||||
pub fn me(&self) -> &Peer {
|
||||
&self.me
|
||||
|
||||
@@ -90,6 +90,8 @@ pub(super) struct Shared {
|
||||
/// Bytes being read into messages, all connections together, and who is reading them.
|
||||
pub(super) reading: Arc<AtomicUsize>,
|
||||
pub(super) readers: Readers,
|
||||
/// The TLS every connection must speak (an app hosting on the network), if any.
|
||||
pub(super) tls: Option<Arc<rustls::ServerConfig>>,
|
||||
}
|
||||
|
||||
pub(super) fn accept(listener: &TcpListener, hub: &Sender<HubIn>, stop: &AtomicBool, open: &Arc<AtomicUsize>, limits: NetLimits, shared: Shared) {
|
||||
@@ -209,12 +211,23 @@ fn serve(mut stream: TcpStream, conn: u64, hub: &Sender<HubIn>, limits: NetLimit
|
||||
if stream.set_read_timeout(Some(limits.hello_timeout)).is_err() || stream.set_write_timeout(Some(limits.write_timeout)).is_err() {
|
||||
return;
|
||||
}
|
||||
if health_check(&mut stream, Instant::now() + limits.hello_timeout) {
|
||||
return;
|
||||
}
|
||||
// Over TLS everything is inside it (an uptime check too, which then isn't answered in the
|
||||
// clear): the handshake comes first, by the hello's deadline.
|
||||
let tls = match &shared.tls {
|
||||
Some(cfg) => match crate::tls::accept(&stream, cfg.clone(), hello_deadline) {
|
||||
Ok(t) => Some(t),
|
||||
Err(e) => {
|
||||
log::debug!("live session: TLS handshake failed: {e}");
|
||||
shutdown(&stream);
|
||||
return;
|
||||
}
|
||||
},
|
||||
None if health_check(&mut stream, Instant::now() + limits.hello_timeout) => return,
|
||||
None => None,
|
||||
};
|
||||
let Ok(peer) = stream.peer_addr().map(|a| a.ip().to_canonical()) else { return };
|
||||
let proxied = limits.trusted_proxy.is_some_and(|p| p.to_canonical() == peer);
|
||||
let Ok((mut rd, wr, sock)) = Duplex::split(stream, None) else { return };
|
||||
let Ok((mut rd, wr, sock)) = Duplex::split(stream, tls) else { return };
|
||||
// The handshake and the hello must be in by the deadline, however slowly they trickle in.
|
||||
rd.read_until(Some(hello_deadline));
|
||||
let cfg = config(limits.max_client_message);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use rustls::ServerConfig;
|
||||
|
||||
use super::backend::Backend;
|
||||
use super::conn::{Shared, accept};
|
||||
use super::limits::PerAddress;
|
||||
@@ -43,10 +45,18 @@ pub struct Hosting {
|
||||
impl Hosting {
|
||||
/// Serve `backend`'s files on `listener`.
|
||||
pub fn serve<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits) -> io::Result<Hosting> {
|
||||
Self::start(listener, backend, limits, None)
|
||||
Self::start(listener, backend, limits, None, None)
|
||||
}
|
||||
|
||||
pub(crate) fn start<B: Backend>(listener: TcpListener, backend: B, limits: NetLimits, local: Option<Local>) -> io::Result<Hosting> {
|
||||
/// Serve on `listener`, with the hosting person in it (`local`), over TLS with `tls` when
|
||||
/// given (every connection must speak it).
|
||||
pub(crate) fn start<B: Backend>(
|
||||
listener: TcpListener,
|
||||
backend: B,
|
||||
limits: NetLimits,
|
||||
local: Option<Local>,
|
||||
tls: Option<Arc<ServerConfig>>,
|
||||
) -> io::Result<Hosting> {
|
||||
let addr = listener.local_addr()?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let in_flight = InFlight(Arc::default());
|
||||
@@ -76,7 +86,9 @@ impl Hosting {
|
||||
blocks: Blocks::default(),
|
||||
reading: Arc::default(),
|
||||
readers: Readers::default(),
|
||||
tls,
|
||||
};
|
||||
let shared_tls = shared.tls.is_some();
|
||||
let queued = shared.queued.clone();
|
||||
let blocks = shared.blocks.clone();
|
||||
let reading = shared.reading.clone();
|
||||
@@ -92,7 +104,7 @@ impl Hosting {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
log::info!("live session: listening on {addr}");
|
||||
log::info!("live session: listening on {addr}{}", if shared_tls { " (TLS)" } else { "" });
|
||||
Ok(Hosting {
|
||||
addr,
|
||||
hub: hub_tx,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
//! Invite links and server addresses.
|
||||
//!
|
||||
//! An app hosting on its local network serves TLS with a certificate of its own (nobody vouches
|
||||
//! for it), so its links name it: `cert=<SHA-256, URL-safe base64>` beside a `wss://` server
|
||||
//! (`figcraft://join?server=wss://…&cert=…&file=…&token=…`, `wss://…/?cert=…&file=…&token=…`). A
|
||||
//! guest then connects only to a host presenting exactly that certificate.
|
||||
//!
|
||||
//! An invite (or share) link names a session's endpoint, its file and a token:
|
||||
//! `figcraft://join?host=<host:port>&file=<id>&token=<secret>` for a plain `ws://` endpoint at `/`
|
||||
//! (what the desktop app hosts), `figcraft://join?server=<ws(s)://host[:port][/path]>&file=…&token=…`
|
||||
@@ -20,6 +25,8 @@
|
||||
//! out the file's team link to whoever asks, while the file is shared. Such a link carries no
|
||||
//! secret: whoever can reach the server may join with it.
|
||||
|
||||
use base64::Engine as _;
|
||||
|
||||
/// Where a session or a server listens: `ws://host:port/path` or `wss://…` (TLS).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Endpoint {
|
||||
@@ -27,8 +34,11 @@ pub struct Endpoint {
|
||||
pub host: String,
|
||||
/// The path it answers on: `/`, or a reverse proxy's prefix (`/figcraft/`).
|
||||
pub path: String,
|
||||
/// `wss://`: TLS (a reverse proxy in front of the server).
|
||||
/// `wss://`: TLS (a reverse proxy in front of the server, or an app's own certificate).
|
||||
pub secure: bool,
|
||||
/// The SHA-256 of the one certificate to accept (`cert=`; `wss://` only), in place of
|
||||
/// checking it with the authorities this computer trusts.
|
||||
pub cert: Option<[u8; 32]>,
|
||||
}
|
||||
|
||||
/// What an invite link names.
|
||||
@@ -53,12 +63,46 @@ pub enum Lookup {
|
||||
/// Longest link accepted (anything longer isn't one of ours).
|
||||
const MAX_LINK: usize = 2048;
|
||||
|
||||
/// The query key of a certificate pin.
|
||||
const CERT: &str = "cert";
|
||||
|
||||
const NOT: &str = "that's not a live session invite: expected figcraft://join?host=…&file=…&token=… or ws://host:port/?file=…&token=…";
|
||||
|
||||
impl Endpoint {
|
||||
/// A plain `ws://host/` endpoint.
|
||||
pub fn plain(host: impl Into<String>) -> Self {
|
||||
Self { host: host.into(), path: "/".into(), secure: false }
|
||||
Self { host: host.into(), path: "/".into(), secure: false, cert: None }
|
||||
}
|
||||
|
||||
/// A `wss://host/` endpoint presenting the certificate `cert` is the SHA-256 of.
|
||||
pub fn pinned(host: impl Into<String>, cert: [u8; 32]) -> Self {
|
||||
Self { host: host.into(), path: "/".into(), secure: true, cert: Some(cert) }
|
||||
}
|
||||
|
||||
/// `cert=…&` for a pinned endpoint (empty otherwise): a link's query starts with it.
|
||||
fn cert_pair(&self) -> String {
|
||||
self.cert.map(|c| format!("{CERT}={}&", B64.encode(c))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Take a `cert=` pin out of `query` into this endpoint: a malformed one, one on a `ws://`
|
||||
/// address, or one that contradicts a pin already there is an error (never ignored, which
|
||||
/// would join without it).
|
||||
fn take_cert(&mut self, query: &mut Vec<(String, String)>) -> Result<(), String> {
|
||||
let mut found = None;
|
||||
for (_, v) in query.extract_if(.., |(k, _)| k == CERT) {
|
||||
let pin = read_cert(&v)?;
|
||||
if found.is_some_and(|f| f != pin) || self.cert.is_some_and(|c| c != pin) {
|
||||
return Err("the link names two different certificates".into());
|
||||
}
|
||||
found = Some(pin);
|
||||
}
|
||||
if let Some(pin) = found {
|
||||
if !self.secure {
|
||||
return Err("the link names a certificate for a ws:// address: a certificate needs wss://".into());
|
||||
}
|
||||
self.cert = Some(pin);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `ws://` at `/`: an invite can name it as `host=…`.
|
||||
@@ -66,7 +110,7 @@ impl Endpoint {
|
||||
!self.secure && self.path == "/"
|
||||
}
|
||||
|
||||
/// The WebSocket URL to connect to (no secrets in it).
|
||||
/// The WebSocket URL to connect to (no secrets in it, nor the pin).
|
||||
pub fn url(&self) -> String {
|
||||
format!("{}://{}{}", if self.secure { "wss" } else { "ws" }, self.host, self.path)
|
||||
}
|
||||
@@ -84,6 +128,17 @@ impl Endpoint {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this endpoint is within an explicitly allowed server origin and path prefix.
|
||||
pub fn is_within(&self, allowed: &Endpoint) -> bool {
|
||||
self.secure == allowed.secure
|
||||
// A pin trusts a certificate no authority checked: only the one allowed.
|
||||
&& self.cert == allowed.cert
|
||||
&& self.host.eq_ignore_ascii_case(&allowed.host)
|
||||
&& safe_path(&self.path)
|
||||
&& safe_path(&allowed.path)
|
||||
&& (allowed.path == "/" || self.path.starts_with(&allowed.path))
|
||||
}
|
||||
|
||||
/// Read `ws(s)://host[:port][/path][?query]` (a missing port is the scheme's: 80 or 443): the
|
||||
/// endpoint and the query's decoded pairs. Errors say what's wrong without echoing `url`.
|
||||
pub fn parse(url: &str) -> Result<(Endpoint, Vec<(String, String)>), String> {
|
||||
@@ -116,7 +171,10 @@ impl Endpoint {
|
||||
if !path.ends_with('/') {
|
||||
path.push('/');
|
||||
}
|
||||
Ok((Endpoint { host, path, secure }, pairs(query)?))
|
||||
let mut query = pairs(query)?;
|
||||
let mut endpoint = Endpoint { host, path, secure, cert: None };
|
||||
endpoint.take_cert(&mut query)?;
|
||||
Ok((endpoint, query))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -131,7 +189,7 @@ impl Invite {
|
||||
if self.server.is_plain() {
|
||||
format!("figcraft://join?host={}&file={}&token={}", self.server.host, self.file, self.token)
|
||||
} else {
|
||||
format!("figcraft://join?server={}&file={}&token={}", self.server.url(), self.file, self.token)
|
||||
format!("figcraft://join?server={}&{}file={}&token={}", self.server.url(), self.server.cert_pair(), self.file, self.token)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,13 +199,13 @@ impl Invite {
|
||||
if self.server.is_plain() {
|
||||
format!("figcraft://join?host={}&file={}&team=1", self.server.host, self.file)
|
||||
} else {
|
||||
format!("figcraft://join?server={}&file={}&team=1", self.server.url(), self.file)
|
||||
format!("figcraft://join?server={}&{}file={}&team=1", self.server.url(), self.server.cert_pair(), self.file)
|
||||
}
|
||||
}
|
||||
|
||||
/// The same session as a WebSocket URL.
|
||||
pub fn url(&self) -> String {
|
||||
format!("{}?file={}&token={}", self.server.url(), self.file, self.token)
|
||||
format!("{}?{}file={}&token={}", self.server.url(), self.server.cert_pair(), self.file, self.token)
|
||||
}
|
||||
|
||||
/// What the client connects to (no secrets in it).
|
||||
@@ -183,16 +241,19 @@ impl Invite {
|
||||
if !path.trim_end_matches('/').eq_ignore_ascii_case("join") {
|
||||
return Err(NOT.into());
|
||||
}
|
||||
let query = pairs(query).map_err(|_| NOT)?;
|
||||
let mut query = pairs(query).map_err(|_| NOT)?;
|
||||
let get = |k: &str| query.iter().find(|(key, _)| key == k).map(|(_, v)| v.clone());
|
||||
let server = match (get("server"), get("host")) {
|
||||
(Some(url), _) => Endpoint::parse(&url).map(|(e, _)| e).map_err(|_| "the invite link's server isn't a ws:// or wss:// address")?,
|
||||
let mut server = match (get("server"), get("host")) {
|
||||
(Some(url), _) => Endpoint::parse(&url)
|
||||
.map(|(e, _)| e)
|
||||
.map_err(|e| if e.contains("certificate") { e } else { "the invite link's server isn't a ws:// or wss:// address".into() })?,
|
||||
(None, Some(host)) if valid_host(&host) => Endpoint::plain(host),
|
||||
_ => return Err("the invite link's host isn't an address with a port (like 192.168.1.20:47900)".into()),
|
||||
};
|
||||
server.take_cert(&mut query)?;
|
||||
(server, query)
|
||||
} else if scheme.eq_ignore_ascii_case("ws") || scheme.eq_ignore_ascii_case("wss") {
|
||||
Endpoint::parse(link).map_err(|e| if e.contains("host") { e } else { NOT.into() })?
|
||||
Endpoint::parse(link).map_err(|e| if e.contains("host") || e.contains("certificate") { e } else { NOT.into() })?
|
||||
} else {
|
||||
return Err(NOT.into());
|
||||
};
|
||||
@@ -211,6 +272,19 @@ impl Invite {
|
||||
}
|
||||
}
|
||||
|
||||
/// URL-safe base64 without padding: how a link writes a certificate's SHA-256.
|
||||
const B64: base64::engine::GeneralPurpose = base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
|
||||
/// A `cert=` value: a SHA-256 in [`B64`] (43 characters). Errors don't echo it.
|
||||
fn read_cert(v: &str) -> Result<[u8; 32], String> {
|
||||
const BAD: &str = "the link's certificate (cert=) isn't a SHA-256 in URL-safe base64";
|
||||
if v.len() != 43 {
|
||||
return Err(BAD.into());
|
||||
}
|
||||
let bytes = B64.decode(v).map_err(|_| BAD)?;
|
||||
<[u8; 32]>::try_from(bytes).map_err(|_| BAD.into())
|
||||
}
|
||||
|
||||
/// Without surrounding spaces, quotes or angle brackets.
|
||||
fn clean(s: &str) -> &str {
|
||||
s.trim().trim_matches(|c| matches!(c, '<' | '>' | '"' | '\''))
|
||||
@@ -261,6 +335,10 @@ fn valid_path(p: &str) -> bool {
|
||||
p.starts_with('/') && p.len() <= 256 && p.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.' | b'~'))
|
||||
}
|
||||
|
||||
fn safe_path(p: &str) -> bool {
|
||||
!p.split('/').any(|part| matches!(part, "." | ".."))
|
||||
}
|
||||
|
||||
/// `%XX` escapes decoded (UTF-8); `None` for broken escapes.
|
||||
fn percent_decode(s: &str) -> Option<String> {
|
||||
let bytes = s.as_bytes();
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
use proptest::prelude::*;
|
||||
|
||||
use figcraft_engine::live::LiveLink;
|
||||
|
||||
use crate::invite::{Endpoint, Invite};
|
||||
|
||||
const TOKEN: &str = "AbCdEfGhIjKlMnOpQrStUv";
|
||||
@@ -39,7 +41,7 @@ fn hosts_can_be_v6_or_names() {
|
||||
#[test]
|
||||
fn server_links_carry_tls_and_a_path() {
|
||||
// A server behind a TLS reverse proxy, under a path: the server= form.
|
||||
let i = Invite { server: Endpoint { host: "figcraft.example.com:443".into(), path: "/live/".into(), secure: true }, ..invite() };
|
||||
let i = Invite { server: Endpoint { host: "figcraft.example.com:443".into(), path: "/live/".into(), secure: true, cert: None }, ..invite() };
|
||||
assert_eq!(i.link(), format!("figcraft://join?server=wss://figcraft.example.com:443/live/&file=0123456789abcdef&token={TOKEN}"));
|
||||
assert_eq!(i.url(), format!("wss://figcraft.example.com:443/live/?file=0123456789abcdef&token={TOKEN}"));
|
||||
assert_eq!(i.endpoint(), "wss://figcraft.example.com:443/live/");
|
||||
@@ -58,13 +60,35 @@ fn server_links_carry_tls_and_a_path() {
|
||||
assert!(plain.link().starts_with("figcraft://join?host=10.0.0.5:47900&"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_automation_server_allowlist_matches_the_parsed_origin_and_path_prefix() {
|
||||
let net = crate::NetLink::new(std::sync::Arc::new(|| {}));
|
||||
let allowed = vec!["wss://figcraft.example.com/team/".to_string()];
|
||||
let invite = |server: &str| Invite { server: Endpoint::parse(server).unwrap().0, ..invite() }.link();
|
||||
|
||||
assert!(net.automation_join_allowed(&invite("wss://FIGCRAFT.example.com/team/live/"), &allowed));
|
||||
assert!(net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/teams/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/../outside/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/live/"), &["wss://figcraft.example.com/team/../".to_string()]));
|
||||
assert!(!net.automation_join_allowed(&invite("ws://figcraft.example.com/team/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com:444/team/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://other.example.com/team/"), &allowed));
|
||||
assert!(!net.automation_join_allowed(
|
||||
"figcraft://join?server=wss://other.example.com/team/&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv",
|
||||
&allowed
|
||||
));
|
||||
assert!(!net.automation_join_allowed("figcraft://join?host=192.168.1.20:47900&file=0123456789abcdef&token=AbCdEfGhIjKlMnOpQrStUv", &allowed));
|
||||
assert!(!net.automation_join_allowed(&invite("wss://figcraft.example.com/team/"), &["wss://figcraft.example.com/team/?key=secret".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_addresses_with_a_key() {
|
||||
let (e, q) = Endpoint::parse("ws://127.0.0.1:47900/?key=KeyKeyKeyKeyKeyKeyKey0").unwrap();
|
||||
assert_eq!(e, Endpoint::plain("127.0.0.1:47900"));
|
||||
assert_eq!(q, vec![("key".to_string(), "KeyKeyKeyKeyKeyKeyKey0".to_string())]);
|
||||
let (e, q) = Endpoint::parse(" wss://example.org ").unwrap();
|
||||
assert_eq!(e, Endpoint { host: "example.org:443".into(), path: "/".into(), secure: true });
|
||||
assert_eq!(e, Endpoint { host: "example.org:443".into(), path: "/".into(), secure: true, cert: None });
|
||||
assert!(q.is_empty());
|
||||
let secret = "SuperSecretToken123456";
|
||||
for bad in [
|
||||
@@ -118,10 +142,18 @@ proptest! {
|
||||
|
||||
#[test]
|
||||
fn valid_invites_round_trip(a in 1u8..255, port in 1u16.., file in "[a-f0-9]{1,64}", token in "[A-Za-z0-9_-]{16,128}", path in "(/[a-z0-9]{1,8}){0,3}", secure: bool) {
|
||||
let i = Invite { server: Endpoint { host: format!("10.0.0.{a}:{port}"), path: format!("{path}/"), secure }, file, token };
|
||||
let i = Invite { server: Endpoint { host: format!("10.0.0.{a}:{port}"), path: format!("{path}/"), secure, cert: None }, file, token };
|
||||
prop_assert_eq!(Invite::parse(&i.link()), Ok(i.clone()));
|
||||
prop_assert_eq!(Invite::parse(&i.url()), Ok(i));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pinned_invites_round_trip(a in 1u8..255, port in 1u16.., pin: [u8; 32], file in "[a-f0-9]{1,64}", token in "[A-Za-z0-9_-]{16,128}") {
|
||||
let i = Invite { server: Endpoint::pinned(format!("10.0.0.{a}:{port}"), pin), file, token };
|
||||
prop_assert_eq!(Invite::parse(&i.link()), Ok(i.clone()));
|
||||
prop_assert_eq!(Invite::parse(&i.url()), Ok(i.clone()));
|
||||
prop_assert_eq!(Invite::parse(&i.team_link().replace("&team=1", &format!("&token={}", i.token))), Ok(i));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -139,3 +171,57 @@ fn port_must_be_all_digits() {
|
||||
assert!(Endpoint::parse(bad).is_err(), "accepted {bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-256 of an app's own certificate, as a link writes it.
|
||||
const PIN: [u8; 32] = [7; 32];
|
||||
const PIN_B64: &str = "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc";
|
||||
|
||||
#[test]
|
||||
fn a_pinned_invite_names_its_certificate_in_both_forms_and_never_in_the_request() {
|
||||
let i = Invite { server: Endpoint::pinned("192.168.1.20:47900", PIN), ..invite() };
|
||||
assert_eq!(i.link(), format!("figcraft://join?server=wss://192.168.1.20:47900/&cert={PIN_B64}&file=0123456789abcdef&token={TOKEN}"));
|
||||
assert_eq!(i.url(), format!("wss://192.168.1.20:47900/?cert={PIN_B64}&file=0123456789abcdef&token={TOKEN}"));
|
||||
for way in [i.link(), i.url()] {
|
||||
let back = Invite::parse(&way).unwrap();
|
||||
assert_eq!((back.server.cert, back.server.secure), (Some(PIN), true), "{way}");
|
||||
}
|
||||
// What the client connects to carries neither the token nor the pin.
|
||||
assert_eq!(i.endpoint(), "wss://192.168.1.20:47900/");
|
||||
// A server address can carry one too (the query's other pairs stay).
|
||||
let (e, query) = Endpoint::parse(&format!("wss://192.168.1.20:47900/?cert={PIN_B64}&key=k")).unwrap();
|
||||
assert_eq!((e.cert, query), (Some(PIN), vec![("key".to_string(), "k".to_string())]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_or_misplaced_certificates_are_refused_without_echoing_the_link() {
|
||||
let other = "CAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg";
|
||||
let rest = format!("file=0123456789abcdef&token={TOKEN}");
|
||||
for bad in [
|
||||
// Not 32 bytes, not URL-safe base64, padded, or with stray bits.
|
||||
format!("wss://10.0.0.1:47900/?cert=BwcH&{rest}"),
|
||||
format!("wss://10.0.0.1:47900/?cert={PIN_B64}A&{rest}"),
|
||||
format!("wss://10.0.0.1:47900/?cert={PIN_B64}=&{rest}"),
|
||||
format!("wss://10.0.0.1:47900/?cert=+wcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc&{rest}"),
|
||||
format!("wss://10.0.0.1:47900/?cert=BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwd&{rest}"),
|
||||
format!("wss://10.0.0.1:47900/?cert=&{rest}"),
|
||||
format!("figcraft://join?server=wss://10.0.0.1:47900/&cert=%ZZ&{rest}"),
|
||||
// On a plain address: never dropped (that would join without it).
|
||||
format!("ws://10.0.0.1:47900/?cert={PIN_B64}&{rest}"),
|
||||
format!("figcraft://join?host=10.0.0.1:47900&cert={PIN_B64}&{rest}"),
|
||||
// Two that disagree.
|
||||
format!("wss://10.0.0.1:47900/?cert={PIN_B64}&cert={other}&{rest}"),
|
||||
format!("figcraft://join?server=wss://10.0.0.1:47900/%3Fcert%3D{PIN_B64}&cert={other}&{rest}"),
|
||||
] {
|
||||
let e = Invite::parse(&bad).expect_err(&bad);
|
||||
assert!(!e.contains(TOKEN) && !e.contains("10.0.0.1") && !e.contains("BwcH"), "{bad}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allowed_server_allows_only_its_own_certificate() {
|
||||
let allowed = Endpoint::pinned("10.0.0.1:47900", PIN);
|
||||
assert!(Endpoint::pinned("10.0.0.1:47900", PIN).is_within(&allowed));
|
||||
assert!(!Endpoint::pinned("10.0.0.1:47900", [8; 32]).is_within(&allowed));
|
||||
let by_authority = Endpoint { cert: None, ..allowed.clone() };
|
||||
assert!(!allowed.is_within(&by_authority), "a pin bypasses the authorities the allowed server is checked with");
|
||||
}
|
||||
@@ -26,6 +26,8 @@ mod requests;
|
||||
mod sessions;
|
||||
pub mod throttle;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod cert;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod guest;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -151,6 +151,15 @@ pub(crate) fn reachable(addr: SocketAddr) -> SocketAddr {
|
||||
}
|
||||
|
||||
impl LiveLink for NetLink {
|
||||
fn automation_join_allowed(&self, link: &str, allowed_servers: &[String]) -> bool {
|
||||
let Ok((invite, _)) = Invite::parse_join(link) else {
|
||||
return false;
|
||||
};
|
||||
allowed_servers
|
||||
.iter()
|
||||
.any(|allowed| Endpoint::parse(allowed).is_ok_and(|(endpoint, query)| query.is_empty() && invite.server.is_within(&endpoint)))
|
||||
}
|
||||
|
||||
/// Host the open file on `o.bind`: a join code's short secret when `o.short`, and a second,
|
||||
/// view-only secret with its invite link when `o.view`.
|
||||
fn host(&mut self, session: SessionId, o: HostOptions) -> Result<SessionInfo, String> {
|
||||
@@ -179,12 +188,19 @@ impl LiveLink for NetLink {
|
||||
name: o.name,
|
||||
limits: self.limits,
|
||||
core: figcraft_collab::Limits::default(),
|
||||
// Reachable from other machines: the token mustn't cross the network in the clear, so
|
||||
// the session serves TLS to its own certificate, which its links pin. A session with a
|
||||
// join code stays plain: a code has no room for the pin, and the code's joiners would
|
||||
// fail against TLS (and share the token with the link's).
|
||||
tls: !ip.is_loopback() && !o.short,
|
||||
};
|
||||
let host = Host::start(cfg, inbox.clone()).map_err(|e| format!("can't listen on {ip}: {e}"))?;
|
||||
// Listening on every interface (`0.0.0.0`, `::`), the links name an address others reach.
|
||||
let at = reachable(host.addr()).to_string();
|
||||
let view = view_token.map(|v| Invite::new(at.clone(), file.clone(), v)).map(|v| WayIn { link: v.link(), url: v.url() });
|
||||
let invite = Invite::new(at.clone(), file, token);
|
||||
let server = host.endpoint(at.clone());
|
||||
let view =
|
||||
view_token.map(|v| Invite { server: server.clone(), file: file.clone(), token: v }).map(|v| WayIn { link: v.link(), url: v.url() });
|
||||
let invite = Invite { server, file, token };
|
||||
let info = SessionInfo {
|
||||
role: Role::Host,
|
||||
me: host.me().client_id,
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Probe {
|
||||
})
|
||||
}
|
||||
|
||||
fn joined(&self) -> Vec<u32> {
|
||||
pub(crate) fn joined(&self) -> Vec<u32> {
|
||||
self.events.iter().filter_map(|e| if let Event::PeerJoined(p) = e { Some(p.client_id) } else { None }).collect()
|
||||
}
|
||||
|
||||
@@ -80,6 +80,12 @@ pub(crate) fn fast_limits() -> NetLimits {
|
||||
|
||||
/// A host on a free loopback port with these limits, a probe of what it is told, and its invite.
|
||||
fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
|
||||
host_on_loopback(limits, core, false)
|
||||
}
|
||||
|
||||
/// A host on a free loopback port, serving TLS with its own certificate when `tls` (its invite
|
||||
/// then pins it), a probe of what it is told, and its invite.
|
||||
pub(crate) fn host_on_loopback(limits: NetLimits, core: Limits, tls: bool) -> (Host, Probe, Invite) {
|
||||
let probe = Probe::new();
|
||||
let mut doc = Document::new("Shared file");
|
||||
doc.repair();
|
||||
@@ -93,9 +99,10 @@ fn start_with(limits: NetLimits, core: Limits) -> (Host, Probe, Invite) {
|
||||
name: "Hana".into(),
|
||||
limits,
|
||||
core,
|
||||
tls,
|
||||
};
|
||||
let host = Host::start(cfg, probe.inbox.clone()).unwrap();
|
||||
let invite = Invite::new(host.addr().to_string(), FILE, TOKEN);
|
||||
let invite = Invite { server: host.endpoint(host.addr().to_string()), file: FILE.into(), token: TOKEN.into() };
|
||||
(host, probe, invite)
|
||||
}
|
||||
|
||||
@@ -189,9 +196,13 @@ fn guests_join_and_see_each_other() {
|
||||
let Some(Event::Welcome { info, peers }) = ap.events.iter().rev().find(|e| matches!(e, Event::Welcome { .. })) else { panic!("no welcome") };
|
||||
assert_eq!(info.name, "Ada");
|
||||
assert!(
|
||||
ap.events.iter().any(
|
||||
|e| matches!(e, Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty())
|
||||
),
|
||||
ap.events.iter().any(|e| matches!(
|
||||
e,
|
||||
Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::Snapshot(snapshot), .. }) if !snapshot.is_empty()
|
||||
) || matches!(
|
||||
e,
|
||||
Event::Sync(ServerMsg::Welcome { catch_up: figcraft_collab::CatchUp::DeltaSnapshot(bytes), .. }) if !bytes.is_empty()
|
||||
)),
|
||||
"the welcome carries the document for the sync client"
|
||||
);
|
||||
assert_eq!(peers.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Hana"], "the host is already here");
|
||||
@@ -274,6 +285,7 @@ fn a_view_token_lets_people_look_and_not_edit() {
|
||||
name: "Hana".into(),
|
||||
limits: fast_limits(),
|
||||
core: Limits::default(),
|
||||
tls: false,
|
||||
}
|
||||
};
|
||||
let same = Host::start(cfg(TOKEN), probe.inbox.clone()).err().expect("a view token equal to the edit token is refused");
|
||||
@@ -314,6 +326,7 @@ fn a_file_with_review_settings_past_the_limits_is_not_shared() {
|
||||
name: "Hana".into(),
|
||||
limits: fast_limits(),
|
||||
core: Limits::default(),
|
||||
tls: false,
|
||||
};
|
||||
let e = Host::start(cfg, probe.inbox.clone()).err().expect("settings past the limits are refused");
|
||||
let text = e.to_string();
|
||||
@@ -670,12 +683,21 @@ fn welcomes_are_packed_only_for_clients_that_read_them() {
|
||||
let addr: SocketAddr = invite.server.host.parse().unwrap();
|
||||
let mut old = Raw::connect(addr);
|
||||
let ClientMsg::Hello(h) = Client::hello(FILE, TOKEN, "Old", "") else { panic!("not a hello") };
|
||||
assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h })));
|
||||
assert!(old.send(&ClientMsg::Hello(Hello { client_version: "0.12.1 signals hosting comments".into(), ..h.clone() })));
|
||||
let Some(ServerMsg::Welcome { catch_up: CatchUp::Snapshot(plain), .. }) = old.next() else { panic!("no plain welcome") };
|
||||
let mut mid = Raw::connect(addr);
|
||||
assert!(mid.send(&ClientMsg::Hello(Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..h })));
|
||||
let Some(mut packed_welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = mid.next() else { panic!("no packed welcome") };
|
||||
message::unpack(&mut packed_welcome, 64 << 20).unwrap();
|
||||
assert!(matches!(packed_welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
|
||||
let mut new = Raw::hello(addr, TOKEN);
|
||||
let Some(mut welcome @ ServerMsg::Welcome { catch_up: CatchUp::Packed(_), .. }) = new.next() else { panic!("no packed welcome") };
|
||||
message::unpack(&mut welcome, 64 << 20).unwrap();
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(s), .. } if s == plain), "the same document");
|
||||
let Some(mut delta_welcome @ ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }) = new.next() else {
|
||||
panic!("no delta snapshot welcome")
|
||||
};
|
||||
message::unpack(&mut delta_welcome, 64 << 20).unwrap();
|
||||
let delta_doc = Client::join(delta_welcome).unwrap().document().clone();
|
||||
let plain_doc = figcraft_collab::Replica::from_snapshot(plain).unwrap().document().clone();
|
||||
assert_eq!(delta_doc, plain_doc, "delta snapshot opens the exact same document");
|
||||
host.stop();
|
||||
}
|
||||
|
||||
@@ -780,6 +802,7 @@ fn a_welcome_over_the_size_limit_says_the_file_is_too_large() {
|
||||
name: "Hana".into(),
|
||||
limits: fast_limits(),
|
||||
core: Limits::default(),
|
||||
tls: false,
|
||||
};
|
||||
let mut host = Host::start(cfg, probe.inbox.clone()).unwrap();
|
||||
let invite = Invite::new(host.addr().to_string(), FILE, TOKEN);
|
||||
|
||||
@@ -250,7 +250,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let limits = NetLimits { idle_timeout: idle, ..NetLimits::default() };
|
||||
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
|
||||
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false, cert: None };
|
||||
let ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
@@ -274,7 +274,7 @@ mod tests {
|
||||
}
|
||||
});
|
||||
let limits = NetLimits { request_reply_timeout: Duration::from_millis(400), ..NetLimits::default() };
|
||||
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false };
|
||||
let server = Endpoint { host: addr.to_string(), path: "/".into(), secure: false, cert: None };
|
||||
let mut ws = connect(&server, &limits, Duration::from_secs(2)).unwrap();
|
||||
let started = std::time::Instant::now();
|
||||
assert!(reply::<()>(&mut ws, &limits, |_| None).is_err());
|
||||
|
||||
@@ -204,7 +204,7 @@ impl Read for Duplex {
|
||||
self.read.set_read_timeout(Some(left))?;
|
||||
}
|
||||
let read = match &self.tls {
|
||||
Some(t) => tls::read(t, &mut self.read, &self.write, buf),
|
||||
Some(t) => tls::read(t, &mut self.read, &self.write, buf, self.deadline),
|
||||
None => self.read.read(buf),
|
||||
};
|
||||
match read {
|
||||
@@ -239,13 +239,17 @@ pub fn shutdown(s: &TcpStream) {
|
||||
let _ = s.shutdown(Shutdown::Both);
|
||||
}
|
||||
|
||||
/// Connect to `server` (through TLS for `wss://`): the reader's and the writer's handles, and the
|
||||
/// Connect to `server` (through TLS for `wss://`, to exactly its pinned certificate when it has one): the reader's and the writer's handles, and the
|
||||
/// socket to shut it down with.
|
||||
pub fn open(server: &Endpoint, timeout: Duration, limits: &NetLimits) -> Result<(Duplex, Duplex, TcpStream), String> {
|
||||
// A plain `ws://localhost` is trusted as this machine (a key may go over it), so only loopback
|
||||
// addresses are connected to: a resolver mapping the name elsewhere must not carry it off-machine.
|
||||
let stream = dial(&server.host, !server.secure && server.loopback(), timeout, limits)?;
|
||||
let tls = if server.secure { Some(tls::handshake(&stream, &server.host)?) } else { None };
|
||||
let tls = match (server.secure, &server.cert) {
|
||||
(true, Some(pin)) => Some(tls::handshake_pinned(&stream, &server.host, pin)?),
|
||||
(true, None) => Some(tls::handshake(&stream, &server.host)?),
|
||||
(false, _) => None,
|
||||
};
|
||||
Duplex::split(stream, tls).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
|
||||
+184
-21
@@ -1,50 +1,128 @@
|
||||
//! TLS for `wss://` addresses (native): rustls with ring, trusting Mozilla's root certificates
|
||||
//! (compiled in) plus any in the PEM file `FIGCRAFT_CA_FILE` names (a private authority or a
|
||||
//! self-signed server). Certificates are always verified.
|
||||
//! TLS for `wss://` addresses (native): rustls with ring, trusting the public root certificates of
|
||||
//! webpki-roots (compiled in), the authorities this computer trusts (its certificate store, unless
|
||||
//! `FIGCRAFT_NO_SYSTEM_ROOTS` is set) and any in the PEM file `FIGCRAFT_CA_FILE` names (a private
|
||||
//! authority or a self-signed server). Certificates are always verified.
|
||||
//!
|
||||
//! A connection's reader and writer threads share one TLS session ([`Tls`]), each holding it only
|
||||
//! to decrypt or encrypt: the reader waits for bytes on its own socket handle without it, and a
|
||||
//! sender takes the socket's write lock first (so records go out in the order they were made),
|
||||
//! encrypts under the session's lock, then writes with only the socket's. Neither waits on the
|
||||
//! network while holding the session, so a send stuck behind a full socket never stops the reader
|
||||
//! from draining what arrives.
|
||||
//! from draining what arrives. The session is a client's or, for an app hosting on the network
|
||||
//! with its own certificate ([`crate::cert`]), a server's ([`accept`]).
|
||||
//!
|
||||
//! A `wss://` address with a `cert=` pin ([`handshake_pinned`]) trusts no authority: the server
|
||||
//! must present exactly the certificate whose SHA-256 the invite names, and prove it holds its key.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::TcpStream;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
|
||||
use std::time::Instant;
|
||||
|
||||
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms};
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use rustls::pki_types::{CertificateDer, ServerName};
|
||||
use rustls::{CertificateError, ClientConfig, ClientConnection, RootCertStore};
|
||||
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
|
||||
use rustls::{
|
||||
CertificateError, ClientConfig, ClientConnection, Connection, DigitallySignedStruct, RootCertStore, ServerConfig, ServerConnection,
|
||||
SignatureScheme,
|
||||
};
|
||||
|
||||
use crate::cert::{Fingerprint, fingerprint};
|
||||
|
||||
/// The variable naming a PEM file of extra certificate authorities to trust.
|
||||
pub const CA_FILE: &str = "FIGCRAFT_CA_FILE";
|
||||
|
||||
/// One connection's TLS session, shared by its reader and writer.
|
||||
pub type Tls = Arc<Mutex<ClientConnection>>;
|
||||
/// The variable that, set, leaves the operating system's certificate store out.
|
||||
pub const NO_SYSTEM_ROOTS: &str = "FIGCRAFT_NO_SYSTEM_ROOTS";
|
||||
|
||||
/// One connection's TLS session (a client's or a server's), shared by its reader and writer.
|
||||
pub type Tls = Arc<Mutex<Connection>>;
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The certificate name in `host` (`name:port`, `[v6]:port`).
|
||||
fn server_name(host: &str) -> Result<ServerName<'static>, String> {
|
||||
let name = host.rsplit_once(':').map_or(host, |(n, _)| n).trim_start_matches('[').trim_end_matches(']');
|
||||
ServerName::try_from(name.to_string()).map_err(|_| format!("{name} isn't a name a certificate can be for"))
|
||||
}
|
||||
|
||||
/// Set up TLS on `stream`, connected to `host` (`name:port`), verifying its certificate.
|
||||
pub fn handshake(stream: &TcpStream, host: &str) -> Result<Tls, String> {
|
||||
let name = host.rsplit_once(':').map_or(host, |(n, _)| n).trim_start_matches('[').trim_end_matches(']');
|
||||
let name = ServerName::try_from(name.to_string()).map_err(|_| format!("{name} isn't a name a certificate can be for"))?;
|
||||
let mut conn = ClientConnection::new(config()?, name).map_err(|e| e.to_string())?;
|
||||
let conn = ClientConnection::new(config()?, server_name(host)?).map_err(|e| e.to_string())?;
|
||||
client_handshake(stream, conn).map_err(|e| explain(host, &e))
|
||||
}
|
||||
|
||||
/// Set up TLS on `stream`, connected to `host`, accepting only the certificate whose SHA-256 is
|
||||
/// `expected` (an invite's `cert=`): no authority is asked, and any other certificate (someone in
|
||||
/// between) is refused before anything is sent.
|
||||
pub fn handshake_pinned(stream: &TcpStream, host: &str, expected: &Fingerprint) -> Result<Tls, String> {
|
||||
let conn = ClientConnection::new(pinned_config(expected)?, server_name(host)?).map_err(|e| e.to_string())?;
|
||||
client_handshake(stream, conn).map_err(|e| match rustls_error(&e) {
|
||||
Some(rustls::Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure)) => format!(
|
||||
"the certificate of {host} isn't the one the invite names: someone may be in between, or the session restarted (ask for a new invite link)"
|
||||
),
|
||||
_ => explain(host, &e),
|
||||
})
|
||||
}
|
||||
|
||||
fn client_handshake(stream: &TcpStream, mut conn: ClientConnection) -> io::Result<Tls> {
|
||||
// Writes are flushed to the socket at once, so the queue never grows.
|
||||
conn.set_buffer_limit(None);
|
||||
while conn.is_handshaking() {
|
||||
conn.complete_io(&mut &*stream).map_err(|e| explain(host, &e))?;
|
||||
conn.complete_io(&mut &*stream)?;
|
||||
}
|
||||
Ok(Arc::new(Mutex::new(conn)))
|
||||
Ok(Arc::new(Mutex::new(Connection::Client(conn))))
|
||||
}
|
||||
|
||||
/// Answer a client's TLS handshake on `stream` with `config`, by `deadline` however slowly its
|
||||
/// bytes come. Restores `stream`'s original write timeout once the handshake completes.
|
||||
pub fn accept(stream: &TcpStream, config: Arc<ServerConfig>, deadline: Instant) -> io::Result<Tls> {
|
||||
let orig_write_timeout = stream.write_timeout()?;
|
||||
let mut conn = ServerConnection::new(config).map_err(io::Error::other)?;
|
||||
conn.set_buffer_limit(None);
|
||||
while conn.is_handshaking() {
|
||||
let left = remaining(deadline)?;
|
||||
if conn.wants_write() {
|
||||
stream.set_write_timeout(Some(left))?;
|
||||
conn.write_tls(&mut &*stream)?;
|
||||
continue;
|
||||
}
|
||||
if conn.wants_read() {
|
||||
stream.set_read_timeout(Some(left))?;
|
||||
if conn.read_tls(&mut &*stream)? == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "TLS handshake ended before completion"));
|
||||
}
|
||||
conn.process_new_packets().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
|
||||
}
|
||||
}
|
||||
while conn.wants_write() {
|
||||
stream.set_write_timeout(Some(remaining(deadline)?))?;
|
||||
conn.write_tls(&mut &*stream)?;
|
||||
}
|
||||
stream.set_write_timeout(orig_write_timeout)?;
|
||||
Ok(Arc::new(Mutex::new(Connection::Server(conn))))
|
||||
}
|
||||
|
||||
fn remaining(deadline: Instant) -> io::Result<std::time::Duration> {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
return Err(io::ErrorKind::TimedOut.into());
|
||||
}
|
||||
Ok(left)
|
||||
}
|
||||
|
||||
fn rustls_error(e: &io::Error) -> Option<&rustls::Error> {
|
||||
e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>())
|
||||
}
|
||||
|
||||
/// Why the TLS handshake with `host` failed, in words.
|
||||
fn explain(host: &str, e: &io::Error) -> String {
|
||||
let why = |c: &CertificateError| match c {
|
||||
CertificateError::UnknownIssuer => format!(
|
||||
"isn't signed by an authority this app trusts (for a private or self-signed certificate, set {CA_FILE} to its authority's PEM file)"
|
||||
"isn't signed by an authority this app trusts (for a private or self-signed certificate, add its authority to this computer's trusted certificates, or set {CA_FILE} to its authority's PEM file)"
|
||||
),
|
||||
CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. } => "is for another name".into(),
|
||||
CertificateError::Expired | CertificateError::ExpiredContext { .. } => "has expired".into(),
|
||||
@@ -52,7 +130,7 @@ fn explain(host: &str, e: &io::Error) -> String {
|
||||
CertificateError::Revoked => "has been revoked".into(),
|
||||
other => format!("isn't valid ({other:?})"),
|
||||
};
|
||||
match e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>()) {
|
||||
match rustls_error(e) {
|
||||
Some(rustls::Error::InvalidCertificate(c)) => format!("the certificate of {host} {}", why(c)),
|
||||
Some(other) => format!("no secure connection to {host} ({other}); is a TLS server answering there?"),
|
||||
None => format!("no secure connection to {host} ({e})"),
|
||||
@@ -67,6 +145,15 @@ fn config() -> Result<Arc<ClientConfig>, String> {
|
||||
|
||||
fn make_config() -> Result<Arc<ClientConfig>, String> {
|
||||
let mut roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||
// A private authority an administrator installed (a company's, a proxy's) is trusted as the
|
||||
// computer's other apps trust it (#2342). An unreadable store adds nothing.
|
||||
if std::env::var_os(NO_SYSTEM_ROOTS).is_none() {
|
||||
let system = rustls_native_certs::load_native_certs();
|
||||
for e in &system.errors {
|
||||
log::warn!("system certificate store: {e}");
|
||||
}
|
||||
roots.add_parsable_certificates(system.certs);
|
||||
}
|
||||
if let Some(path) = std::env::var_os(CA_FILE) {
|
||||
let shown = std::path::Path::new(&path).display().to_string();
|
||||
let certs: Vec<CertificateDer> = CertificateDer::pem_file_iter(&path)
|
||||
@@ -78,7 +165,7 @@ fn make_config() -> Result<Arc<ClientConfig>, String> {
|
||||
}
|
||||
#[cfg(test)]
|
||||
roots.add(CertificateDer::from(&include_bytes!("testdata/test-ca.der")[..])).map_err(|e| e.to_string())?;
|
||||
let config = ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
let config = ClientConfig::builder_with_provider(provider())
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.with_root_certificates(roots)
|
||||
@@ -86,19 +173,95 @@ fn make_config() -> Result<Arc<ClientConfig>, String> {
|
||||
Ok(Arc::new(config))
|
||||
}
|
||||
|
||||
/// The ring provider every connection uses.
|
||||
fn provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(rustls::crypto::ring::default_provider())
|
||||
}
|
||||
|
||||
/// Client settings trusting only the certificate `expected` is the SHA-256 of.
|
||||
fn pinned_config(expected: &Fingerprint) -> Result<Arc<ClientConfig>, String> {
|
||||
let provider = provider();
|
||||
let verifier = Pinned { expected: *expected, algorithms: provider.signature_verification_algorithms };
|
||||
let config = ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(|e| e.to_string())?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(verifier))
|
||||
.with_no_client_auth();
|
||||
Ok(Arc::new(config))
|
||||
}
|
||||
|
||||
/// Accepts the one certificate an invite pins, and only a handshake signed with its key.
|
||||
#[derive(Debug)]
|
||||
struct Pinned {
|
||||
expected: Fingerprint,
|
||||
algorithms: WebPkiSupportedAlgorithms,
|
||||
}
|
||||
|
||||
/// `a == b`, in a time that doesn't depend on where they differ.
|
||||
fn same(a: &Fingerprint, b: &Fingerprint) -> bool {
|
||||
a.iter().zip(b).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for Pinned {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
end_entity: &CertificateDer<'_>,
|
||||
_intermediates: &[CertificateDer<'_>],
|
||||
_server_name: &ServerName<'_>,
|
||||
_ocsp_response: &[u8],
|
||||
_now: UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
if same(&fingerprint(end_entity.as_ref()), &self.expected) {
|
||||
Ok(ServerCertVerified::assertion())
|
||||
} else {
|
||||
Err(rustls::Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure))
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls12_signature(message, cert, dss, &self.algorithms)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
rustls::crypto::verify_tls13_signature(message, cert, dss, &self.algorithms)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.algorithms.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Read plaintext into `buf`: what the session has, else wait for bytes on `sock` (outside the
|
||||
/// session's lock), take them in and try again. Anything the session must answer (alerts, key
|
||||
/// updates) goes out through `out`.
|
||||
pub fn read(tls: &Mutex<ClientConnection>, sock: &mut TcpStream, out: &Mutex<TcpStream>, buf: &mut [u8]) -> io::Result<usize> {
|
||||
/// session's lock), take them in and try again. When `deadline` is set, every socket read is
|
||||
/// bounded by the time remaining so trickled ciphertext fragments cannot outlast it. Anything the
|
||||
/// session must answer (alerts, key updates) goes out through `out`.
|
||||
pub fn read(tls: &Mutex<Connection>, sock: &mut TcpStream, out: &Mutex<TcpStream>, buf: &mut [u8], deadline: Option<Instant>) -> io::Result<usize> {
|
||||
loop {
|
||||
match lock(tls).reader().read(buf) {
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {}
|
||||
done => return done,
|
||||
}
|
||||
if let Some(d) = deadline {
|
||||
sock.set_read_timeout(Some(remaining(d)?))?;
|
||||
}
|
||||
// Wait for ciphertext without taking it off the socket, then let the session read only
|
||||
// what it takes: its plaintext buffer is empty here, so it never overflows (feeding it a
|
||||
// whole chunk could, when a record completes on top of plaintext not yet read).
|
||||
sock.peek(&mut [0u8; 1])?;
|
||||
if let Some(d) = deadline {
|
||||
sock.set_read_timeout(Some(remaining(d)?))?;
|
||||
}
|
||||
let answer = {
|
||||
let mut c = lock(tls);
|
||||
// An empty read (the socket ended) tells the session so: the next read ends too.
|
||||
@@ -113,14 +276,14 @@ pub fn read(tls: &Mutex<ClientConnection>, sock: &mut TcpStream, out: &Mutex<Tcp
|
||||
}
|
||||
|
||||
/// Encrypt and send all of `buf`.
|
||||
pub fn write(tls: &Mutex<ClientConnection>, out: &Mutex<TcpStream>, buf: &[u8]) -> io::Result<usize> {
|
||||
pub fn write(tls: &Mutex<Connection>, out: &Mutex<TcpStream>, buf: &[u8]) -> io::Result<usize> {
|
||||
send(tls, out, buf)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
/// Encrypt `plain` and send it after whatever the session has waiting (see the module's docs for
|
||||
/// the locking).
|
||||
fn send(tls: &Mutex<ClientConnection>, out: &Mutex<TcpStream>, plain: &[u8]) -> io::Result<()> {
|
||||
fn send(tls: &Mutex<Connection>, out: &Mutex<TcpStream>, plain: &[u8]) -> io::Result<()> {
|
||||
let mut w = lock(out);
|
||||
let mut records = Vec::new();
|
||||
{
|
||||
|
||||
@@ -1,20 +1,24 @@
|
||||
//! Joining over `wss://`: a guest and a managing connection reach a host through a TLS terminator
|
||||
//! (like the reverse proxy in front of a server) whose certificate comes from a test authority
|
||||
//! only test builds trust; a certificate for another name is refused with a clear reason.
|
||||
//! only test builds trust; a certificate for another name is refused with a clear reason. An app
|
||||
//! hosting with its own certificate is joined through the pin in its invite, and only through it:
|
||||
//! a plain client, or a host presenting another certificate (someone in between), gets nothing.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use figcraft_collab::Limits;
|
||||
use figcraft_engine::live::{Event, Status};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
use rustls::{ServerConfig, ServerConnection, StreamOwned};
|
||||
|
||||
use crate::guest::{Guest, GuestConfig};
|
||||
use crate::invite::{Endpoint, Invite};
|
||||
use crate::loopback_tests::{Probe, fast_limits, quick, start};
|
||||
use crate::loopback_tests::{Probe, fast_limits, host_on_loopback, quick, start};
|
||||
use crate::manage;
|
||||
use crate::net::NetLimits;
|
||||
|
||||
/// Serve `localhost`'s test certificate on a port of `localhost` and relay each connection to
|
||||
/// `upstream`.
|
||||
@@ -67,7 +71,7 @@ fn relay(s: TcpStream, upstream: SocketAddr, cfg: Arc<ServerConfig>) {
|
||||
}
|
||||
|
||||
fn secure(host: String, invite: &Invite) -> Invite {
|
||||
Invite { server: Endpoint { host, path: "/".into(), secure: true }, ..invite.clone() }
|
||||
Invite { server: Endpoint { host, path: "/".into(), secure: true, cert: None }, ..invite.clone() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -111,7 +115,7 @@ fn reader_and_writer_share_one_session_without_blocking_each_other() {
|
||||
let _ = io::copy(&mut s.try_clone().unwrap(), &mut s);
|
||||
});
|
||||
let front = terminator(upstream);
|
||||
let server = Endpoint { host: format!("localhost:{}", front.port()), path: "/".into(), secure: true };
|
||||
let server = Endpoint { host: format!("localhost:{}", front.port()), path: "/".into(), secure: true, cert: None };
|
||||
let (mut rd, mut wr, _sock) = crate::net::open(&server, Duration::from_secs(5), &fast_limits()).unwrap();
|
||||
rd.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
|
||||
let sent: Vec<u8> = (0..8 << 20).map(|i: u32| (i % 251) as u8).collect();
|
||||
@@ -122,3 +126,168 @@ fn reader_and_writer_share_one_session_without_blocking_each_other() {
|
||||
writer.join().unwrap();
|
||||
assert!(got == expect);
|
||||
}
|
||||
|
||||
/// The loopback hosts' token.
|
||||
const TOKEN_OF_TESTS: &str = "AbCdEfGhIjKlMnOpQrStUv";
|
||||
|
||||
fn tls_host() -> (crate::host::Host, Probe, Invite) {
|
||||
host_on_loopback(fast_limits(), Limits::default(), true)
|
||||
}
|
||||
|
||||
fn failed(e: &[Event]) -> Option<&str> {
|
||||
e.iter().find_map(|e| match e {
|
||||
Event::Status(Status::Failed { reason }) => Some(reason.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_host_with_its_own_certificate_is_joined_through_the_pin() {
|
||||
let (mut host, mut hp, invite) = tls_host();
|
||||
let pin = host.cert_sha256().unwrap();
|
||||
assert_eq!((invite.server.secure, invite.server.cert), (true, Some(pin)));
|
||||
assert!(invite.link().contains("cert=") && invite.url().starts_with("wss://"), "{}", invite.link());
|
||||
// Joined from the link, as someone pasting it would; the document comes over TLS.
|
||||
let mut probe = Probe::new();
|
||||
let mut g = Guest::start(quick(GuestConfig::new(Invite::parse(&invite.link()).unwrap(), "Ada".into())), probe.inbox.clone()).unwrap();
|
||||
probe.wait("the welcome over pinned TLS", |e| e.iter().any(|e| matches!(e, Event::Welcome { .. })));
|
||||
hp.wait("the guest in the host's session", |e| e.iter().any(|e| matches!(e, Event::PeerJoined(_))));
|
||||
g.leave();
|
||||
host.stop();
|
||||
}
|
||||
|
||||
/// Someone in between (here: another host with the same file and token, and a certificate of its
|
||||
/// own) is refused before the guest says anything: the token never reaches it.
|
||||
#[test]
|
||||
fn a_host_presenting_another_certificate_is_refused_before_the_hello() {
|
||||
let (mut real, _rp, invite) = tls_host();
|
||||
let (mut mitm, mut mp, posing) = tls_host();
|
||||
assert_ne!(real.cert_sha256(), mitm.cert_sha256());
|
||||
let pinned_to_real = Invite { server: Endpoint { host: posing.server.host.clone(), ..invite.server.clone() }, ..invite };
|
||||
let mut probe = Probe::new();
|
||||
let _g = Guest::start(quick(GuestConfig::new(pinned_to_real, "Ada".into())), probe.inbox.clone()).unwrap();
|
||||
probe.wait("the refusal", |e| failed(e).is_some());
|
||||
let reason = failed(&probe.events).unwrap();
|
||||
assert!(reason.contains("isn't the one the invite names"), "{reason}");
|
||||
assert!(!reason.contains(TOKEN_OF_TESTS) && !reason.contains("cert="), "{reason}");
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
mp.events.extend(mp.inbox.drain());
|
||||
assert!(mp.joined().is_empty(), "the impostor admitted the guest: {:#?}", mp.events);
|
||||
assert!(!probe.events.iter().any(|e| matches!(e, Event::Welcome { .. })));
|
||||
mitm.stop();
|
||||
real.stop();
|
||||
}
|
||||
|
||||
/// A plain `ws://` client gets no session from a TLS host, and soon knows it.
|
||||
#[test]
|
||||
fn a_plain_client_cant_join_a_tls_host() {
|
||||
let (mut host, mut hp, invite) = tls_host();
|
||||
let plain = Invite::new(invite.server.host.clone(), invite.file.clone(), invite.token.clone());
|
||||
let mut probe = Probe::new();
|
||||
let started = Instant::now();
|
||||
let _g = Guest::start(quick(GuestConfig::new(plain, "Ada".into())), probe.inbox.clone()).unwrap();
|
||||
probe.wait("the failure", |e| failed(e).is_some());
|
||||
assert!(started.elapsed() < fast_limits().hello_timeout, "{:?}", started.elapsed());
|
||||
hp.events.extend(hp.inbox.drain());
|
||||
assert!(hp.joined().is_empty());
|
||||
host.stop();
|
||||
}
|
||||
|
||||
/// The WebSocket request to a pinned host names neither the token nor the pin.
|
||||
#[test]
|
||||
fn the_request_to_a_pinned_host_carries_no_secret() {
|
||||
let cert = crate::cert::generate().unwrap();
|
||||
let cfg = crate::cert::server_config(&cert).unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let (s, _) = listener.accept().unwrap();
|
||||
s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
|
||||
let mut tls = StreamOwned::new(ServerConnection::new(cfg).unwrap(), s);
|
||||
let mut req = Vec::new();
|
||||
let mut b = [0u8; 1];
|
||||
while !req.ends_with(b"\r\n\r\n") && tls.read_exact(&mut b).is_ok() {
|
||||
req.push(b[0]);
|
||||
}
|
||||
let _ = tx.send(String::from_utf8_lossy(&req).into_owned());
|
||||
});
|
||||
let invite = Invite { server: Endpoint::pinned(addr.to_string(), cert.sha256), file: "0123456789abcdef".into(), token: TOKEN_OF_TESTS.into() };
|
||||
let _g = Guest::start(quick(GuestConfig::new(invite, "Ada".into())), Probe::new().inbox.clone()).unwrap();
|
||||
let req = rx.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
let line = req.lines().next().unwrap_or_default();
|
||||
assert!(line.starts_with("GET / "), "{req}");
|
||||
assert!(!req.contains(TOKEN_OF_TESTS) && !req.contains("cert"), "{req}");
|
||||
}
|
||||
|
||||
/// A peer that trickles TLS ClientHello bytes slowly cannot stretch `tls::accept` past its deadline.
|
||||
#[test]
|
||||
fn a_trickled_tls_handshake_respects_the_deadline() {
|
||||
let cert = crate::cert::generate().unwrap();
|
||||
let cfg = crate::cert::server_config(&cert).unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let trickle = std::thread::spawn(move || {
|
||||
let mut s = TcpStream::connect(addr).unwrap();
|
||||
// Partial TLS record header: 1 byte every 25ms, far past the 120ms deadline.
|
||||
for b in [0x16u8, 0x03, 0x01, 0x00, 0x20, 0x01, 0x00, 0x00, 0x1c, 0x03, 0x03, 0x00] {
|
||||
if s.write_all(&[b]).is_err() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(25));
|
||||
}
|
||||
});
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let started = Instant::now();
|
||||
let deadline = started + Duration::from_millis(120);
|
||||
let err = crate::tls::accept(&stream, cfg, deadline).unwrap_err();
|
||||
assert!(matches!(err.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock), "expected timeout, got {err:?}");
|
||||
assert!(started.elapsed() < Duration::from_millis(400), "trickled handshake outlasted deadline: {:?}", started.elapsed());
|
||||
drop(stream);
|
||||
let _ = trickle.join();
|
||||
}
|
||||
|
||||
/// After the TLS handshake, a peer that sends an application-data record one byte at a time, each
|
||||
/// in time for a read timeout, is dropped at the hello deadline like a plain one.
|
||||
#[test]
|
||||
fn a_record_trickled_in_after_the_tls_handshake_does_not_outlast_the_hello_deadline() {
|
||||
let limits = NetLimits { hello_timeout: Duration::from_secs(1), ..fast_limits() };
|
||||
let (mut host, _hp, invite) = host_on_loopback(limits, Limits::default(), true);
|
||||
let mut sock = TcpStream::connect(&invite.server.host).unwrap();
|
||||
crate::tls::handshake_pinned(&sock, &invite.server.host, &host.cert_sha256().unwrap()).unwrap();
|
||||
// A record header announcing 16 KiB that never all arrive.
|
||||
sock.write_all(&[0x17, 0x03, 0x03, 0x40, 0x00]).unwrap();
|
||||
sock.set_read_timeout(Some(Duration::from_millis(300))).unwrap();
|
||||
let t0 = Instant::now();
|
||||
let mut closed = None;
|
||||
while closed.is_none() && t0.elapsed() < Duration::from_secs(6) {
|
||||
let ended = sock.write_all(&[0]).is_err()
|
||||
|| match sock.read(&mut [0u8; 256]) {
|
||||
Ok(n) => n == 0,
|
||||
Err(e) => !matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut),
|
||||
};
|
||||
closed = ended.then(|| t0.elapsed());
|
||||
}
|
||||
host.stop();
|
||||
assert!(closed.is_some_and(|t| t < Duration::from_secs(3)), "trickled record survived: {closed:?}");
|
||||
}
|
||||
|
||||
/// `tls::accept` restores the socket's pre-handshake write timeout after finishing.
|
||||
#[test]
|
||||
fn accept_restores_the_configured_write_timeout() {
|
||||
let cert = crate::cert::generate().unwrap();
|
||||
let cfg = crate::cert::server_config(&cert).unwrap();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let sha = cert.sha256;
|
||||
let client = std::thread::spawn(move || {
|
||||
let sock = TcpStream::connect(addr).unwrap();
|
||||
crate::tls::handshake_pinned(&sock, &addr.to_string(), &sha).unwrap();
|
||||
});
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let configured = Some(Duration::from_secs(17));
|
||||
stream.set_write_timeout(configured).unwrap();
|
||||
let _tls = crate::tls::accept(&stream, cfg, Instant::now() + Duration::from_secs(2)).unwrap();
|
||||
assert_eq!(stream.write_timeout().unwrap(), configured);
|
||||
let _ = client.join();
|
||||
}
|
||||
@@ -142,6 +142,11 @@ fn js_error(e: &wasm_bindgen::JsValue) -> String {
|
||||
/// Whether this page may reach `server`: an `https://` page can't open an unencrypted `ws://`
|
||||
/// connection, except to this machine.
|
||||
fn reachable(server: &Endpoint) -> Result<(), String> {
|
||||
// A browser checks certificates against its authorities only: it can't hold a connection to
|
||||
// the one certificate an app's invite pins.
|
||||
if server.cert.is_some() {
|
||||
return Err("that session is hosted by an app on its local network with its own certificate, which a browser can't check: join it from the desktop app".into());
|
||||
}
|
||||
let secure_page = web_sys::window().and_then(|w| w.location().protocol().ok()).is_some_and(|p| p == "https:");
|
||||
if secure_page && !server.secure && !server.loopback() {
|
||||
return Err("this page was loaded over https, and browsers block unencrypted ws:// connections; use a wss:// address (a server behind TLS), open FigCraft from an http:// address (like http://localhost:8767), or use the desktop app".into());
|
||||
|
||||
@@ -18,7 +18,7 @@ fn a_boards_kind_and_its_objects_metadata_sync() {
|
||||
// A joiner's copy, built from the snapshot, is a board with the sticky's metadata.
|
||||
let snap = host.snapshot().unwrap();
|
||||
assert!(snap.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Kind, .. })));
|
||||
let joiner = Replica::from_snapshot(&snap).unwrap();
|
||||
let joiner = Replica::from_snapshot(snap).unwrap();
|
||||
assert_eq!(joiner.document().kind, FileKind::Board);
|
||||
assert_eq!(joiner.document().node(a).unwrap().board, host.document().node(a).unwrap().board);
|
||||
// Re-attaching a connector's end is one property write, the same after the wire.
|
||||
|
||||
@@ -45,6 +45,9 @@ impl<'de> Deserialize<'de> for Json {
|
||||
f.write_str("JSON text")
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Json, E> {
|
||||
// A full snapshot holds one of these per property: while one is read, on the web
|
||||
// the heap grows in large steps ([`crate::heap`]).
|
||||
crate::heap::keep_ahead();
|
||||
// serde_json caps nesting depth, so hostile input can't overflow the stack.
|
||||
serde_json::from_str(v).map(Json).map_err(E::custom)
|
||||
}
|
||||
|
||||
+44
-23
@@ -86,10 +86,19 @@ impl Client {
|
||||
|
||||
/// Start from the server's `Welcome` (which must carry a snapshot).
|
||||
pub fn join(welcome: ServerMsg) -> Result<Client, Error> {
|
||||
let ServerMsg::Welcome { session, client_id, seq, catch_up: CatchUp::Snapshot(snapshot), processed, peers, access, secret } = welcome else {
|
||||
let ServerMsg::Welcome { session, client_id, seq, catch_up, processed, peers, access, secret } = welcome else {
|
||||
return Err(Error::Protocol("expected a welcome with the document".into()));
|
||||
};
|
||||
let mut confirmed = Replica::from_snapshot(&snapshot)?;
|
||||
let mut confirmed = match catch_up {
|
||||
CatchUp::Snapshot(snapshot) => Replica::from_snapshot(snapshot)?,
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
let limits = crate::Limits::default();
|
||||
crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?
|
||||
}
|
||||
CatchUp::Delta(_) | CatchUp::Packed(_) => {
|
||||
return Err(Error::Protocol("expected a welcome with the document".into()));
|
||||
}
|
||||
};
|
||||
confirmed.document_mut().set_client_id(client_id);
|
||||
let next_id = confirmed.document().next_id();
|
||||
Ok(Client {
|
||||
@@ -595,28 +604,15 @@ impl Client {
|
||||
}
|
||||
}
|
||||
CatchUp::Snapshot(snapshot) => {
|
||||
let mut confirmed = Replica::from_snapshot(&snapshot)?;
|
||||
let mut confirmed = Replica::from_snapshot(snapshot)?;
|
||||
confirmed.document_mut().set_client_id(self.id);
|
||||
self.confirmed = confirmed;
|
||||
self.seq = seq;
|
||||
// What the server accepted meanwhile is in the snapshot. Which of the batches since
|
||||
// were others' isn't known, so the steps check every value they wrote below.
|
||||
while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
|
||||
self.pending.pop_front();
|
||||
if processed.refused.contains(&p.batch_id) {
|
||||
self.refused(&p, offline());
|
||||
} else if p.kind != BatchKind::FollowUp
|
||||
&& let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
|
||||
{
|
||||
s.settle(p.kind);
|
||||
}
|
||||
}
|
||||
for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
|
||||
s.verify(&self.confirmed)?;
|
||||
}
|
||||
for p in &mut self.pending {
|
||||
p.rebased = true;
|
||||
}
|
||||
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
|
||||
}
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
let limits = crate::Limits::default();
|
||||
let mut confirmed = crate::delta_snapshot::decode_delta_snapshot(&bytes, 1 << 30, limits.max_nodes)?;
|
||||
confirmed.document_mut().set_client_id(self.id);
|
||||
self.rejoin_with_confirmed(confirmed, seq, last_batch, processed)?;
|
||||
}
|
||||
}
|
||||
if self.seq != seq {
|
||||
@@ -636,6 +632,31 @@ impl Client {
|
||||
Ok(self.flush(recompute))
|
||||
}
|
||||
|
||||
fn rejoin_with_confirmed(&mut self, confirmed: Replica, seq: u64, last_batch: u64, processed: &Processed) -> Result<(), Error> {
|
||||
let offline = || "it no longer applied when the connection came back".to_string();
|
||||
self.confirmed = confirmed;
|
||||
self.seq = seq;
|
||||
// What the server accepted meanwhile is in the snapshot. Which of the batches since
|
||||
// were others' isn't known, so the steps check every value they wrote below.
|
||||
while let Some(p) = self.pending.front().filter(|p| p.batch_id <= last_batch).cloned() {
|
||||
self.pending.pop_front();
|
||||
if processed.refused.contains(&p.batch_id) {
|
||||
self.refused(&p, offline());
|
||||
} else if p.kind != BatchKind::FollowUp
|
||||
&& let Some(s) = p.step.and_then(|id| find_step(&mut self.undo, &mut self.redo, id))
|
||||
{
|
||||
s.settle(p.kind);
|
||||
}
|
||||
}
|
||||
for s in self.undo.iter_mut().chain(self.redo.iter_mut()).filter(|s| s.confirmed) {
|
||||
s.verify(&self.confirmed)?;
|
||||
}
|
||||
for p in &mut self.pending {
|
||||
p.rebased = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A session that doesn't know this client (it restarted without its saved state) welcomed
|
||||
/// it as new: start over from its document; unconfirmed work and the undo history are gone.
|
||||
fn restart(&mut self, welcome: ServerMsg) -> Result<Vec<ClientMsg>, Error> {
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Multi-seed mixed-version DST for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Document, NodeId};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::delta_snapshot::{decode_delta_snapshot, encode_delta_snapshot};
|
||||
use crate::delta_snapshot_tests::{LEGACY_CLIENT_VERSION, assert_docs_json_eq, design_system_doc};
|
||||
use crate::message::{CatchUp, ClientMsg, Hello, ServerMsg};
|
||||
use crate::sim::Rng;
|
||||
use crate::{Client, Limits, NoRecompute, Outgoing, Server};
|
||||
|
||||
fn deliver_outgoing(clients: &mut [(Client, Hello, bool)], outs: Vec<Outgoing>) {
|
||||
for out in outs {
|
||||
match out {
|
||||
Outgoing::All(m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Outgoing::To(target, m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() && c.id() == target {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
Outgoing::Others(skip, m) => {
|
||||
for (c, _, _) in clients.iter_mut() {
|
||||
if c.is_online() && c.id() != skip {
|
||||
let _ = c.receive(m.clone(), &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reconnect_dst_client(server: &mut Server, clients: &mut [(Client, Hello, bool)], idx: usize) -> (bool, bool) {
|
||||
let (c, base_h, delta_capable) = &mut clients[idx];
|
||||
let ClientMsg::Hello(mut rh) = c.reconnect(base_h.clone()) else { panic!("expected Hello") };
|
||||
if !*delta_capable {
|
||||
rh.client_version = base_h.client_version.clone();
|
||||
}
|
||||
let (id, outs) = server.join(rh).unwrap();
|
||||
let welcome = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
let is_delta_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. });
|
||||
let is_legacy_snap = matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. });
|
||||
let follow = c.receive(welcome, &NoRecompute).unwrap();
|
||||
let cid = c.id();
|
||||
for msg in follow {
|
||||
let rep = server.receive(cid, msg);
|
||||
deliver_outgoing(clients, rep);
|
||||
}
|
||||
(is_delta_snap, is_legacy_snap)
|
||||
}
|
||||
|
||||
fn apply_random_dst_edit(edited: &mut Document, rng: &mut Rng, comp: NodeId, main_children: &[NodeId], seed: u64, step: usize) {
|
||||
let all_ids: Vec<NodeId> = edited.ids().filter(|id| !edited.node(*id).unwrap().is_page()).collect();
|
||||
match rng.below(4) {
|
||||
0 => {
|
||||
let target = *rng.pick(main_children).unwrap();
|
||||
if let Some(n) = edited.node_mut(target) {
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(rng.below(255) as u8, 80, 140))];
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
let text_mirrors: Vec<NodeId> =
|
||||
all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some() && n.kind.text().is_some())).collect();
|
||||
if let Some(&target) = rng.pick(&text_mirrors)
|
||||
&& let Some(n) = edited.node_mut(target)
|
||||
{
|
||||
if let Some(t) = n.kind.text_mut() {
|
||||
t.characters = format!("S{seed}-T{step}");
|
||||
}
|
||||
if rng.chance(0.5) {
|
||||
n.overrides.clear();
|
||||
} else {
|
||||
n.overrides.insert("characters".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
let mirrors: Vec<NodeId> = all_ids.iter().copied().filter(|id| edited.node(*id).is_some_and(|n| n.source.is_some())).collect();
|
||||
if let Some(&target) = rng.pick(&mirrors)
|
||||
&& let Some(n) = edited.node_mut(target)
|
||||
{
|
||||
n.transform = Affine::translate((rng.below(400) as f64, rng.below(200) as f64));
|
||||
n.width = 20.0 + rng.below(120) as f64;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(n) = edited.node_mut(comp) {
|
||||
n.name = format!("Card-v{step}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_dst_invariants(server: &Server, clients: &[(Client, Hello, bool)], seed: u64, step: usize) {
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(server.replica()).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
|
||||
assert_docs_json_eq(server.document(), decoded.document(), &format!("seed={seed} step={step} roundtrip"));
|
||||
for (i, (c, _, _)) in clients.iter().enumerate() {
|
||||
if c.is_online() {
|
||||
assert_docs_json_eq(server.document(), c.document(), &format!("seed={seed} step={step} client {i}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn run_dst_seed(seed: u64) {
|
||||
let mut rng = Rng::new(seed);
|
||||
let (doc, comp, main_children) = design_system_doc(6);
|
||||
let limits = Limits { max_log_batches: 2, ..Limits::default() };
|
||||
let mut server = Server::new(doc, "dst-secret", limits);
|
||||
|
||||
let join_client = |srv: &mut Server, name: &str, delta_capable: bool| -> (Client, Hello) {
|
||||
let ClientMsg::Hello(mut h) = Client::hello("dst", "dst-secret", name, "#2266EE") else { panic!() };
|
||||
if !delta_capable {
|
||||
h.client_version = LEGACY_CLIENT_VERSION.into();
|
||||
}
|
||||
let (id, outs) = srv.join(h.clone()).unwrap();
|
||||
let welcome = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
if delta_capable {
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::DeltaSnapshot(_), .. }));
|
||||
} else {
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }));
|
||||
}
|
||||
(Client::join(welcome).unwrap(), h)
|
||||
};
|
||||
|
||||
let (c0, h0) = join_client(&mut server, "Delta-A", true);
|
||||
let (c1, h1) = join_client(&mut server, "Delta-B", true);
|
||||
let (c2, h2) = join_client(&mut server, "Legacy-C", false);
|
||||
let mut clients = vec![(c0, h0, true), (c1, h1, true), (c2, h2, false)];
|
||||
let (mut delta_snap_rejoins, mut legacy_snap_rejoins) = (0usize, 0usize);
|
||||
|
||||
for step in 0..30usize {
|
||||
if step == 15 {
|
||||
let saved = server.state().unwrap();
|
||||
server = Server::restore(saved, "dst-secret", limits).unwrap();
|
||||
for (c, _, _) in &mut clients {
|
||||
c.disconnect();
|
||||
}
|
||||
for idx in 0..clients.len() {
|
||||
let _ = reconnect_dst_client(&mut server, &mut clients, idx);
|
||||
}
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
continue;
|
||||
}
|
||||
|
||||
if step == 6 || step == 20 {
|
||||
let victim = if step == 6 { 1 } else { 2 };
|
||||
clients[victim].0.disconnect();
|
||||
server.leave(clients[victim].0.id());
|
||||
|
||||
let mut off_doc = clients[victim].0.document().clone();
|
||||
if let Some(p) = off_doc.first_page()
|
||||
&& let Some(n) = off_doc.node_mut(p)
|
||||
{
|
||||
n.name = format!("Offline-{seed}-{step}");
|
||||
}
|
||||
let _ = clients[victim].0.edit(&off_doc).unwrap();
|
||||
|
||||
for sub in 0..4 {
|
||||
let mut edited = clients[0].0.document().clone();
|
||||
apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step * 10 + sub);
|
||||
if let Some(msg) = clients[0].0.edit(&edited).unwrap() {
|
||||
let outs = server.receive(clients[0].0.id(), msg);
|
||||
deliver_outgoing(&mut clients, outs);
|
||||
}
|
||||
}
|
||||
|
||||
let (was_delta, was_legacy) = reconnect_dst_client(&mut server, &mut clients, victim);
|
||||
delta_snap_rejoins += usize::from(was_delta);
|
||||
legacy_snap_rejoins += usize::from(was_legacy);
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
continue;
|
||||
}
|
||||
|
||||
let actor_idx = rng.below(clients.len());
|
||||
let mut edited = clients[actor_idx].0.document().clone();
|
||||
apply_random_dst_edit(&mut edited, &mut rng, comp, &main_children, seed, step);
|
||||
if let Some(msg) = clients[actor_idx].0.edit(&edited).unwrap() {
|
||||
let outs = server.receive(clients[actor_idx].0.id(), msg);
|
||||
deliver_outgoing(&mut clients, outs);
|
||||
}
|
||||
assert_dst_invariants(&server, &clients, seed, step);
|
||||
}
|
||||
|
||||
assert!(delta_snap_rejoins > 0 && legacy_snap_rejoins > 0, "seed={seed}: must exercise both snapshot rejoin paths");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_mixed_delta_and_legacy_clients_converge_under_faults_and_restarts() {
|
||||
let seeds: Vec<u64> = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse::<u64>().ok()) {
|
||||
Some(single) => vec![single],
|
||||
None => vec![1, 7, 42, 1337, 2026],
|
||||
};
|
||||
for seed in seeds {
|
||||
run_dst_seed(seed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
//! Streaming decode and memory-budget enforcement for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::fmt;
|
||||
use std::io::Read;
|
||||
use std::mem::size_of;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_doc::color::Paint;
|
||||
use figcraft_doc::proto::Interaction;
|
||||
use figcraft_doc::{
|
||||
Annotation, CodeLink, DevResource, Document, Effect, ExportSetting, Guide, LayoutGrid, Measurement, Node, NodeId, NodeKind, Region, Segment,
|
||||
VectorNetwork, Vertex,
|
||||
};
|
||||
use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
|
||||
|
||||
use super::fields::{FieldDelta, apply_field_delta};
|
||||
use super::{DEFAULT_MAX_MATERIALIZED_BYTES, HEADER_LEN, WireMeta, WireRecord, parse_header};
|
||||
use crate::Error;
|
||||
use crate::docprops::{clamp_design_review_config, validate_image_base64};
|
||||
use crate::frac;
|
||||
use crate::replica::{Positions, Replica};
|
||||
|
||||
/// Maximum ratio of estimated materialized bytes to declared uncompressed JSON bytes.
|
||||
/// Heavy design-system files sit around 15x to 35x; amplification bombs exceed 1,000x.
|
||||
const MAX_AMPLIFICATION_FACTOR: usize = 64;
|
||||
const MIN_MATERIALIZED_FLOOR: usize = 16 << 20;
|
||||
|
||||
/// Effective materialized-byte ceiling shared by encoder and decoder.
|
||||
pub(super) fn materialized_budget(declared: usize, ceiling: usize) -> usize {
|
||||
let cap = declared.saturating_mul(MAX_AMPLIFICATION_FACTOR).max(MIN_MATERIALIZED_FLOOR);
|
||||
ceiling.min(cap)
|
||||
}
|
||||
|
||||
/// Decode a compressed `CatchUp::DeltaSnapshot` payload into a validated [`Replica`].
|
||||
pub fn decode_delta_snapshot(bytes: &[u8], max_bytes: usize, max_nodes: usize) -> Result<Replica, Error> {
|
||||
decode_delta_snapshot_with_budget(bytes, max_bytes, max_nodes, DEFAULT_MAX_MATERIALIZED_BYTES)
|
||||
}
|
||||
|
||||
/// Decode a compressed `CatchUp::DeltaSnapshot` with an explicit ceiling on estimated
|
||||
/// materialized memory, also capped at `max(16 MiB, 64 * declared_bytes)`.
|
||||
pub fn decode_delta_snapshot_with_budget(bytes: &[u8], max_bytes: usize, max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
|
||||
let _reading = crate::heap::reading();
|
||||
let declared = parse_header(bytes)?;
|
||||
if declared > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
let body = bytes.get(HEADER_LEN..).ok_or_else(|| Error::Decode("delta snapshot body missing".into()))?;
|
||||
// Stop inflating at `declared + 1` so a forged small length aborts immediately.
|
||||
let limit = u64::try_from(declared).unwrap_or(u64::MAX).saturating_add(1);
|
||||
let prealloc = declared.min(bytes.len().saturating_mul(8)).min(1 << 20);
|
||||
let mut raw = Vec::with_capacity(prealloc);
|
||||
flate2::read::DeflateDecoder::new(body).take(limit).read_to_end(&mut raw).map_err(|e| Error::Decode(format!("delta snapshot deflate: {e}")))?;
|
||||
if raw.len() > declared {
|
||||
return Err(Error::TooLarge(declared));
|
||||
}
|
||||
if raw.len() != declared {
|
||||
return Err(Error::Decode(format!("delta snapshot truncated: header declared {declared} bytes, inflated {}", raw.len())));
|
||||
}
|
||||
|
||||
stream_decode_wire(&raw, max_nodes, materialized_budget(declared, max_materialized_bytes))
|
||||
}
|
||||
|
||||
fn est_str_map(m: &BTreeMap<String, String>) -> usize {
|
||||
m.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len()).saturating_add(48))
|
||||
}
|
||||
|
||||
pub(super) fn est_vector_bytes(net: &VectorNetwork) -> usize {
|
||||
let regs = net.regions.iter().fold(0usize, |acc, r| {
|
||||
let loops = r.loops.iter().fold(0usize, |a, l| a.saturating_add(l.len().saturating_mul(size_of::<usize>())));
|
||||
let fills = r.fills.as_ref().map_or(0, |f| f.len().saturating_mul(size_of::<Paint>()));
|
||||
acc.saturating_add(size_of::<Region>()).saturating_add(loops).saturating_add(fills)
|
||||
});
|
||||
size_of::<VectorNetwork>()
|
||||
.saturating_add(net.vertices.len().saturating_mul(size_of::<Vertex>()))
|
||||
.saturating_add(net.segments.len().saturating_mul(size_of::<Segment>()))
|
||||
.saturating_add(regs)
|
||||
}
|
||||
|
||||
fn est_kind_bytes(kind: &NodeKind) -> usize {
|
||||
match kind {
|
||||
NodeKind::Vector { network } => est_vector_bytes(network),
|
||||
NodeKind::Text(t) => t.characters.len().saturating_add(t.runs.len().saturating_mul(64)),
|
||||
NodeKind::Component { description, props, prop_order } => {
|
||||
description.len().saturating_add(props.len().saturating_mul(96)).saturating_add(prop_order.len().saturating_mul(32))
|
||||
}
|
||||
NodeKind::Instance { props, .. } => props.len().saturating_mul(96),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn est_node_bytes(n: &Node) -> usize {
|
||||
let ov: usize = n.overrides.iter().fold(0, |a, s| a.saturating_add(s.len()).saturating_add(24));
|
||||
size_of::<Node>()
|
||||
.saturating_add(n.name.len())
|
||||
.saturating_add(n.dev_note.len())
|
||||
.saturating_add(n.fills.len().saturating_mul(size_of::<Paint>()))
|
||||
.saturating_add(n.strokes.len().saturating_mul(size_of::<Paint>()))
|
||||
.saturating_add(n.effects.len().saturating_mul(size_of::<Effect>()))
|
||||
.saturating_add(n.grids.len().saturating_mul(size_of::<LayoutGrid>()))
|
||||
.saturating_add(n.guides.len().saturating_mul(size_of::<Guide>()))
|
||||
.saturating_add(n.exports.len().saturating_mul(size_of::<ExportSetting>()))
|
||||
.saturating_add(n.interactions.len().saturating_mul(size_of::<Interaction>()))
|
||||
.saturating_add(n.annotations.len().saturating_mul(size_of::<Annotation>()))
|
||||
.saturating_add(n.code_links.len().saturating_mul(size_of::<CodeLink>()))
|
||||
.saturating_add(n.dev_resources.len().saturating_mul(size_of::<DevResource>()))
|
||||
.saturating_add(n.measurements.len().saturating_mul(size_of::<Measurement>()))
|
||||
.saturating_add(est_kind_bytes(&n.kind))
|
||||
.saturating_add(ov)
|
||||
.saturating_add(est_str_map(&n.bound))
|
||||
.saturating_add(est_str_map(&n.var_modes))
|
||||
.saturating_add(est_str_map(&n.plugin_data))
|
||||
.saturating_add(est_str_map(&n.prop_refs))
|
||||
}
|
||||
|
||||
pub(super) fn est_deltas_extra_bytes(deltas: &[FieldDelta], vector_sizes: &[usize]) -> usize {
|
||||
deltas.iter().fold(0usize, |acc, d| {
|
||||
let extra = match d {
|
||||
FieldDelta::Name(s) | FieldDelta::DevNote(s) => s.len(),
|
||||
FieldDelta::Kind(k) => est_kind_bytes(k),
|
||||
FieldDelta::VectorRef(idx) => usize::try_from(*idx).ok().and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0),
|
||||
FieldDelta::Fills(v) | FieldDelta::Strokes(v) => v.len().saturating_mul(size_of::<Paint>()),
|
||||
FieldDelta::Effects(v) => v.len().saturating_mul(size_of::<Effect>()),
|
||||
FieldDelta::Bound(m) | FieldDelta::VarModes(m) | FieldDelta::PluginData(m) | FieldDelta::PropRefs(m) => est_str_map(m),
|
||||
FieldDelta::Annotations(v) => v.len().saturating_mul(size_of::<Annotation>()),
|
||||
FieldDelta::CodeLinks(v) => v.len().saturating_mul(size_of::<CodeLink>()),
|
||||
_ => 0,
|
||||
};
|
||||
acc.saturating_add(extra)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn est_meta_bytes(meta: &WireMeta) -> usize {
|
||||
let images = meta.images.iter().fold(0usize, |a, i| a.saturating_add(i.key.len()).saturating_add(i.bytes.len()));
|
||||
let comments = meta.comments.iter().fold(0usize, |a, c| {
|
||||
let replies = c.replies.iter().fold(0usize, |r, m| r.saturating_add(m.author.len()).saturating_add(m.text.len()).saturating_add(64));
|
||||
a.saturating_add(c.first.author.len()).saturating_add(c.first.text.len()).saturating_add(replies).saturating_add(128)
|
||||
});
|
||||
let styles = meta.styles.iter().fold(0usize, |a, s| a.saturating_add(s.id.len()).saturating_add(s.name.len()).saturating_add(128));
|
||||
let dev_snaps = meta.dev_snapshots.values().fold(0usize, |a, s| s.nodes.iter().fold(a, |b, n| b.saturating_add(est_node_bytes(n))));
|
||||
let vars = meta.variables.collections.len().saturating_mul(128).saturating_add(meta.variables.variables.len().saturating_mul(128));
|
||||
let libs = meta.libraries.components.len().saturating_mul(128).saturating_add(meta.libraries.styles.len().saturating_mul(128));
|
||||
let votes = meta.votes.iter().fold(0usize, |a, (k, v)| a.saturating_add(k.len()).saturating_add(v.len().saturating_mul(size_of::<NodeId>())));
|
||||
let categories = meta
|
||||
.annotation_categories
|
||||
.iter()
|
||||
.flatten()
|
||||
.fold(0usize, |a, c| a.saturating_add(c.id.len()).saturating_add(c.name.len()).saturating_add(128));
|
||||
meta.name
|
||||
.len()
|
||||
.saturating_add(images)
|
||||
.saturating_add(comments)
|
||||
.saturating_add(styles)
|
||||
.saturating_add(dev_snaps)
|
||||
.saturating_add(vars)
|
||||
.saturating_add(libs)
|
||||
.saturating_add(votes)
|
||||
.saturating_add(categories)
|
||||
.saturating_add(meta.vote_history.len().saturating_mul(128))
|
||||
.saturating_add(meta.image_presets.len().saturating_mul(64))
|
||||
.saturating_add(meta.document_colors.len().saturating_mul(32))
|
||||
}
|
||||
|
||||
struct DecodeState {
|
||||
doc: Document,
|
||||
positions: Positions,
|
||||
touched: BTreeSet<NodeId>,
|
||||
vectors: Vec<figcraft_doc::Shared<VectorNetwork>>,
|
||||
vector_sizes: Vec<usize>,
|
||||
node_sizes: HashMap<NodeId, usize>,
|
||||
meta: Option<WireMeta>,
|
||||
records_seen: usize,
|
||||
max_nodes: usize,
|
||||
materialized_bytes: usize,
|
||||
max_materialized_bytes: usize,
|
||||
abort: Option<Error>,
|
||||
}
|
||||
|
||||
impl DecodeState {
|
||||
fn new(max_nodes: usize, max_materialized_bytes: usize) -> Self {
|
||||
Self {
|
||||
doc: Document::without_pages(""),
|
||||
positions: Positions::new(),
|
||||
touched: BTreeSet::new(),
|
||||
vectors: Vec::new(),
|
||||
vector_sizes: Vec::new(),
|
||||
node_sizes: HashMap::new(),
|
||||
meta: None,
|
||||
records_seen: 0,
|
||||
max_nodes,
|
||||
materialized_bytes: 0,
|
||||
max_materialized_bytes,
|
||||
abort: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn charge(&mut self, bytes: usize) -> Result<(), Error> {
|
||||
self.materialized_bytes = self.materialized_bytes.saturating_add(bytes);
|
||||
if self.materialized_bytes > self.max_materialized_bytes {
|
||||
return Err(Error::TooLarge(self.max_materialized_bytes));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fail<E: de::Error>(&mut self, err: Error) -> E {
|
||||
let msg = err.to_string();
|
||||
self.abort = Some(err);
|
||||
E::custom(msg)
|
||||
}
|
||||
|
||||
fn ingest_record(&mut self, rec: WireRecord) -> Result<(), Error> {
|
||||
let (node, pos, size) = match rec {
|
||||
WireRecord::Full { pos, mut node, vref } => {
|
||||
frac::validate(&pos).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
if self.doc.contains(node.id) {
|
||||
return Err(Error::Invalid(format!("node {} already exists", node.id)));
|
||||
}
|
||||
node.children.clear();
|
||||
let mut est = est_node_bytes(&node).saturating_add(pos.len());
|
||||
if let Some(idx) = vref {
|
||||
let i = usize::try_from(idx).map_err(|_| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
let vsize = self.vector_sizes.get(i).copied().ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
est = est.saturating_add(vsize);
|
||||
self.charge(est)?;
|
||||
let net = self.vectors.get(i).ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
} else {
|
||||
self.charge(est)?;
|
||||
}
|
||||
(*node, pos, est)
|
||||
}
|
||||
WireRecord::Mirror(m) => {
|
||||
frac::validate(&m.pos).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
if self.doc.contains(m.id) {
|
||||
return Err(Error::Invalid(format!("node {} already exists", m.id)));
|
||||
}
|
||||
let missing = || Error::Invalid(format!("mirror {} references missing or cyclic source {}", m.id, m.source));
|
||||
let src_size = self.node_sizes.get(&m.source).copied().ok_or_else(missing)?;
|
||||
let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &self.vector_sizes)).saturating_add(m.pos.len());
|
||||
self.charge(est)?;
|
||||
let src = self.doc.node(m.source).ok_or_else(missing)?;
|
||||
let mut node = src.clone();
|
||||
node.id = m.id;
|
||||
node.parent = m.parent;
|
||||
node.children.clear();
|
||||
node.source = Some(m.source);
|
||||
node.overrides = m.overrides;
|
||||
for delta in m.deltas {
|
||||
apply_field_delta(&mut node, delta, &self.vectors)?;
|
||||
}
|
||||
let actual = est_node_bytes(&node).saturating_add(m.pos.len());
|
||||
(node, m.pos, actual)
|
||||
}
|
||||
};
|
||||
|
||||
let id = node.id;
|
||||
insert_decoded_node(&mut self.doc, &mut self.positions, node, pos)?;
|
||||
self.touched.insert(id);
|
||||
self.node_sizes.insert(id, size);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct VectorsSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for VectorsSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for VectorsSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("vector networks")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
|
||||
while let Some(net) = seq.next_element::<VectorNetwork>()? {
|
||||
let size = est_vector_bytes(&net);
|
||||
if let Err(err) = self.0.charge(size) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
self.0.vector_sizes.push(size);
|
||||
self.0.vectors.push(figcraft_doc::Shared::new(net));
|
||||
crate::heap::keep_ahead();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct RecordsSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for RecordsSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_seq(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for RecordsSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("delta snapshot records")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<(), A::Error> {
|
||||
loop {
|
||||
if self.0.records_seen >= self.0.max_nodes {
|
||||
if seq.next_element::<de::IgnoredAny>()?.is_some() {
|
||||
let max = self.0.max_nodes;
|
||||
return Err(self.0.fail(Error::Invalid(format!("delta snapshot exceeds the {max}-node limit"))));
|
||||
}
|
||||
break;
|
||||
}
|
||||
let Some(rec) = seq.next_element::<WireRecord>()? else {
|
||||
break;
|
||||
};
|
||||
self.0.records_seen += 1;
|
||||
if let Err(err) = self.0.ingest_record(rec) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
crate::heap::keep_ahead();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct DeltaWireSeed<'a>(&'a mut DecodeState);
|
||||
impl<'de> DeserializeSeed<'de> for DeltaWireSeed<'_> {
|
||||
type Value = ();
|
||||
fn deserialize<D: de::Deserializer<'de>>(self, d: D) -> Result<(), D::Error> {
|
||||
d.deserialize_map(self)
|
||||
}
|
||||
}
|
||||
impl<'de> Visitor<'de> for DeltaWireSeed<'_> {
|
||||
type Value = ();
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("delta snapshot payload")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
match key.as_str() {
|
||||
"meta" => {
|
||||
let meta: WireMeta = map.next_value()?;
|
||||
if let Err(err) = self.0.charge(est_meta_bytes(&meta)) {
|
||||
return Err(self.0.fail(err));
|
||||
}
|
||||
self.0.meta = Some(meta);
|
||||
}
|
||||
"vectors" => map.next_value_seed(VectorsSeed(self.0))?,
|
||||
"records" => map.next_value_seed(RecordsSeed(self.0))?,
|
||||
_ => {
|
||||
let _ = map.next_value::<de::IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_decode_wire(raw: &[u8], max_nodes: usize, max_materialized_bytes: usize) -> Result<Replica, Error> {
|
||||
let mut state = DecodeState::new(max_nodes, max_materialized_bytes);
|
||||
let mut de = serde_json::Deserializer::from_slice(raw);
|
||||
let res = DeltaWireSeed(&mut state).deserialize(&mut de);
|
||||
if let Some(err) = state.abort {
|
||||
return Err(err);
|
||||
}
|
||||
res.map_err(|e| Error::Decode(format!("delta snapshot json: {e}")))?;
|
||||
de.end().map_err(|e| Error::Decode(format!("delta snapshot trailing data: {e}")))?;
|
||||
|
||||
let meta = state.meta.ok_or_else(|| Error::Decode("delta snapshot missing meta".into()))?;
|
||||
apply_meta(&mut state.doc, meta);
|
||||
relist_pages(&mut state.doc, &state.positions);
|
||||
if state.doc.pages.is_empty() {
|
||||
return Err(Error::Invalid("a snapshot needs a page".into()));
|
||||
}
|
||||
state.doc.published = None;
|
||||
state.doc.take_dirty();
|
||||
let replica = Replica::from_parts(state.doc, state.positions);
|
||||
replica.check(&state.touched)?;
|
||||
Ok(replica)
|
||||
}
|
||||
|
||||
fn insert_decoded_node(doc: &mut Document, positions: &mut Positions, node: Node, pos: String) -> Result<(), Error> {
|
||||
let (id, is_page, parent) = (node.id, node.is_page(), node.parent);
|
||||
match (is_page, parent) {
|
||||
(true, None) => {
|
||||
doc.insert_page(node).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
}
|
||||
(false, Some(p)) => {
|
||||
let siblings = &doc.get(p).map_err(|e| Error::Invalid(e.to_string()))?.children;
|
||||
let at = siblings.partition_point(|c| (positions.get(c).map_or("", String::as_str), *c) < (pos.as_str(), id));
|
||||
doc.insert(node, p, Some(at)).map_err(|e| Error::Invalid(e.to_string()))?;
|
||||
}
|
||||
_ => return Err(Error::Invalid("pages, and only pages, have no parent".into())),
|
||||
}
|
||||
positions.insert(id, pos);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn apply_meta(doc: &mut Document, mut meta: WireMeta) {
|
||||
doc.name = meta.name;
|
||||
doc.kind = meta.kind;
|
||||
doc.styles = meta.styles;
|
||||
doc.variables = meta.variables;
|
||||
doc.current_page = meta.current_page;
|
||||
doc.document_colors = meta.document_colors;
|
||||
doc.comments = meta.comments;
|
||||
doc.libraries = Arc::new(meta.libraries);
|
||||
doc.color_profile = meta.color_profile;
|
||||
doc.image_presets = meta.image_presets;
|
||||
clamp_design_review_config(&mut meta.design_review);
|
||||
doc.design_review = meta.design_review;
|
||||
doc.annotation_categories = meta.annotation_categories;
|
||||
doc.dev_snapshots = meta.dev_snapshots.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
|
||||
doc.timer = meta.timer;
|
||||
doc.vote = meta.vote;
|
||||
doc.votes = meta.votes;
|
||||
doc.vote_history = meta.vote_history;
|
||||
for wi in meta.images {
|
||||
// Leave out images that fail validation or attempt to replace bytes under an existing
|
||||
// key, matching legacy `Replica::from_snapshot_leaving_out`.
|
||||
let Ok(img) = validate_image_base64(&wi.key, wi.width, wi.height, &wi.bytes) else {
|
||||
continue;
|
||||
};
|
||||
if doc.images.get(&wi.key).is_some_and(|old| old.bytes != img.bytes) {
|
||||
continue;
|
||||
}
|
||||
doc.images.insert(wi.key, img);
|
||||
}
|
||||
}
|
||||
|
||||
fn relist_pages(doc: &mut Document, positions: &Positions) {
|
||||
let store = doc.libraries.store;
|
||||
let mut pages: Vec<NodeId> = doc.nodes().filter(|n| n.is_page() && Some(n.id) != store).map(|n| n.id).collect();
|
||||
pages.sort_by(|a, b| (positions.get(a).map_or("", String::as_str), *a).cmp(&(positions.get(b).map_or("", String::as_str), *b)));
|
||||
doc.pages = pages;
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Topological ordering, vector interning and deflate framing for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::io::{BufWriter, Write};
|
||||
|
||||
use figcraft_doc::{Document, Node, NodeId, NodeKind, VectorNetwork};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
|
||||
use super::decode::{est_deltas_extra_bytes, est_meta_bytes, est_node_bytes, est_vector_bytes, materialized_budget};
|
||||
use super::fields::{diff_mirror_fields, exact_vector_network_eq};
|
||||
use super::{DEFAULT_MAX_MATERIALIZED_BYTES, DELTA_MAGIC, DELTA_VERSION, DeltaWireRef, MirrorWire, WireImage, WireMeta, WireRecord};
|
||||
use crate::Error;
|
||||
use crate::replica::Replica;
|
||||
|
||||
/// Content-addressed deduplicator for `VectorNetwork`s within one snapshot.
|
||||
#[derive(Default)]
|
||||
pub(super) struct VectorInterner {
|
||||
by_hash: HashMap<[u8; 32], Vec<u32>>,
|
||||
table: Vec<VectorNetwork>,
|
||||
}
|
||||
|
||||
impl VectorInterner {
|
||||
pub(super) fn intern(&mut self, net: &VectorNetwork) -> Result<u32, Error> {
|
||||
let raw = serde_json::to_vec(net).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
let digest: [u8; 32] = Sha256::digest(&raw).into();
|
||||
if let Some(bucket) = self.by_hash.get(&digest) {
|
||||
for &idx in bucket {
|
||||
if usize::try_from(idx).ok().and_then(|i| self.table.get(i)).is_some_and(|existing| exact_vector_network_eq(existing, net)) {
|
||||
return Ok(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
let idx = u32::try_from(self.table.len()).map_err(|_| Error::Encode("too many distinct vector networks".into()))?;
|
||||
self.table.push(net.clone());
|
||||
self.by_hash.entry(digest).or_default().push(idx);
|
||||
Ok(idx)
|
||||
}
|
||||
}
|
||||
|
||||
/// Kahn topological order over `(parent, source)` edges (in-degree at most 2 per node).
|
||||
///
|
||||
/// Every parent precedes its children and every acyclic source precedes its mirrors. Nodes
|
||||
/// caught in a `source` cycle are appended in parent-first order and emitted as `Full`.
|
||||
fn topo_order(doc: &Document) -> Vec<NodeId> {
|
||||
let mut roots = doc.pages.clone();
|
||||
roots.extend(doc.nodes().filter(|n| n.parent.is_none() && !doc.pages.contains(&n.id)).map(|n| n.id));
|
||||
let mut parent_order = Vec::with_capacity(doc.node_count());
|
||||
for r in roots {
|
||||
parent_order.extend(doc.subtree(r));
|
||||
}
|
||||
|
||||
let present: HashSet<NodeId> = parent_order.iter().copied().collect();
|
||||
let mut indeg: HashMap<NodeId, u8> = HashMap::with_capacity(present.len());
|
||||
let mut deps_of: HashMap<NodeId, Vec<NodeId>> = HashMap::with_capacity(present.len());
|
||||
|
||||
for &id in &parent_order {
|
||||
let Some(n) = doc.node(id) else { continue };
|
||||
let mut d: u8 = 0;
|
||||
let p = n.parent.filter(|p| *p != id && present.contains(p));
|
||||
let s = n.source.filter(|s| *s != id && Some(*s) != p && present.contains(s));
|
||||
if let Some(pid) = p {
|
||||
deps_of.entry(pid).or_default().push(id);
|
||||
d += 1;
|
||||
}
|
||||
if let Some(sid) = s {
|
||||
deps_of.entry(sid).or_default().push(id);
|
||||
d += 1;
|
||||
}
|
||||
indeg.insert(id, d);
|
||||
}
|
||||
|
||||
let mut q: VecDeque<NodeId> = parent_order.iter().copied().filter(|id| indeg.get(id).copied() == Some(0)).collect();
|
||||
let mut ordered = Vec::with_capacity(parent_order.len());
|
||||
let mut placed: HashSet<NodeId> = HashSet::with_capacity(parent_order.len());
|
||||
|
||||
while let Some(u) = q.pop_front() {
|
||||
if !placed.insert(u) {
|
||||
continue;
|
||||
}
|
||||
ordered.push(u);
|
||||
if let Some(nexts) = deps_of.get(&u) {
|
||||
for &v in nexts {
|
||||
if let Some(deg) = indeg.get_mut(&v)
|
||||
&& *deg > 0
|
||||
{
|
||||
*deg -= 1;
|
||||
if *deg == 0 {
|
||||
q.push_back(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ordered.len() < parent_order.len() {
|
||||
for id in parent_order {
|
||||
if placed.insert(id) {
|
||||
ordered.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
ordered
|
||||
}
|
||||
|
||||
/// Encode `replica` as a compressed `CatchUp::DeltaSnapshot` payload.
|
||||
///
|
||||
/// Returns `Error::TooLarge` if the payload would exceed the client decoder's materialized-memory
|
||||
/// budget, allowing callers such as `Server::join_as` to fall back to `CatchUp::Snapshot`.
|
||||
pub fn encode_delta_snapshot(replica: &Replica) -> Result<Vec<u8>, Error> {
|
||||
let doc = replica.document();
|
||||
let order = topo_order(doc);
|
||||
let mut interner = VectorInterner::default();
|
||||
let mut seen: HashMap<NodeId, &Node> = HashMap::with_capacity(order.len());
|
||||
let mut records = Vec::with_capacity(order.len());
|
||||
|
||||
for id in order {
|
||||
let Some(node) = doc.node(id) else { continue };
|
||||
let pos = replica.key(id).to_string();
|
||||
let rec = encode_one_node(node, pos, &seen, &mut interner)?;
|
||||
records.push(rec);
|
||||
seen.insert(id, node);
|
||||
}
|
||||
|
||||
let meta = build_meta(doc);
|
||||
let est_materialized = estimate_decode_charge(&meta, &interner.table, &records);
|
||||
let wire = DeltaWireRef { meta: &meta, vectors: &interner.table, records: &records };
|
||||
let (out, written) = compress_wire(&wire)?;
|
||||
let budget = materialized_budget(written, DEFAULT_MAX_MATERIALIZED_BYTES);
|
||||
if est_materialized > budget {
|
||||
return Err(Error::TooLarge(budget));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Mirror the decoder's materialized-byte accounting so the server never emits a delta snapshot
|
||||
/// that a compliant client would reject with `Error::TooLarge`.
|
||||
fn estimate_decode_charge(meta: &WireMeta, vectors: &[VectorNetwork], records: &[WireRecord]) -> usize {
|
||||
let vector_sizes: Vec<usize> = vectors.iter().map(est_vector_bytes).collect();
|
||||
let mut total = est_meta_bytes(meta);
|
||||
for &vs in &vector_sizes {
|
||||
total = total.saturating_add(vs);
|
||||
}
|
||||
let mut node_sizes: HashMap<NodeId, usize> = HashMap::with_capacity(records.len());
|
||||
for rec in records {
|
||||
match rec {
|
||||
WireRecord::Full { pos, node, vref } => {
|
||||
let vsize = vref.and_then(|idx| usize::try_from(idx).ok()).and_then(|i| vector_sizes.get(i).copied()).unwrap_or(0);
|
||||
let est = est_node_bytes(node).saturating_add(pos.len()).saturating_add(vsize);
|
||||
total = total.saturating_add(est);
|
||||
node_sizes.insert(node.id, est);
|
||||
}
|
||||
WireRecord::Mirror(m) => {
|
||||
let src_size = node_sizes.get(&m.source).copied().unwrap_or(0);
|
||||
let est = src_size.saturating_add(est_deltas_extra_bytes(&m.deltas, &vector_sizes)).saturating_add(m.pos.len());
|
||||
let overrides = m.overrides.iter().fold(0usize, |a, s| a.saturating_add(s.len()).saturating_add(24));
|
||||
total = total.saturating_add(est);
|
||||
node_sizes.insert(m.id, est.saturating_add(overrides));
|
||||
}
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn encode_one_node(node: &Node, pos: String, seen: &HashMap<NodeId, &Node>, interner: &mut VectorInterner) -> Result<WireRecord, Error> {
|
||||
if let Some(src_id) = node.source
|
||||
&& let Some(src) = seen.get(&src_id)
|
||||
{
|
||||
let deltas = diff_mirror_fields(src, node, interner)?;
|
||||
return Ok(WireRecord::Mirror(Box::new(MirrorWire {
|
||||
id: node.id,
|
||||
parent: node.parent,
|
||||
pos,
|
||||
source: src_id,
|
||||
overrides: node.overrides.clone(),
|
||||
deltas,
|
||||
})));
|
||||
}
|
||||
|
||||
let mut stripped = node.clone();
|
||||
// Children are rebuilt from `(parent, pos)` on decode.
|
||||
stripped.children.clear();
|
||||
let vref = match &mut stripped.kind {
|
||||
NodeKind::Vector { network } if !network.vertices.is_empty() || !network.segments.is_empty() || !network.regions.is_empty() => {
|
||||
let idx = interner.intern(network)?;
|
||||
*network = figcraft_doc::Shared::default();
|
||||
Some(idx)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
Ok(WireRecord::Full { pos, node: Box::new(stripped), vref })
|
||||
}
|
||||
|
||||
fn build_meta(doc: &Document) -> WireMeta {
|
||||
use base64::Engine as _;
|
||||
let images = doc
|
||||
.images
|
||||
.iter()
|
||||
.map(|(key, img)| WireImage {
|
||||
key: key.clone(),
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
bytes: base64::engine::general_purpose::STANDARD.encode(img.bytes.as_slice()),
|
||||
})
|
||||
.collect();
|
||||
WireMeta {
|
||||
name: doc.name.clone(),
|
||||
kind: doc.kind,
|
||||
styles: doc.styles.clone(),
|
||||
variables: doc.variables.clone(),
|
||||
current_page: doc.current_page,
|
||||
document_colors: doc.document_colors.clone(),
|
||||
comments: doc.comments.clone(),
|
||||
libraries: (*doc.libraries).clone(),
|
||||
color_profile: doc.color_profile,
|
||||
image_presets: doc.image_presets.clone(),
|
||||
design_review: doc.design_review.clone(),
|
||||
annotation_categories: doc.annotation_categories.clone(),
|
||||
dev_snapshots: doc.dev_snapshots.iter().map(|(k, v)| (*k, (**v).clone())).collect(),
|
||||
timer: doc.timer,
|
||||
vote: doc.vote.clone(),
|
||||
votes: doc.votes.clone(),
|
||||
vote_history: doc.vote_history.clone(),
|
||||
images,
|
||||
}
|
||||
}
|
||||
|
||||
struct CountingWriter<W> {
|
||||
inner: W,
|
||||
written: usize,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for CountingWriter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.write(buf)?;
|
||||
self.written = self.written.saturating_add(n);
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
fn compress_wire(wire: &DeltaWireRef<'_>) -> Result<(Vec<u8>, usize), Error> {
|
||||
let mut out = Vec::with_capacity(4096);
|
||||
out.extend_from_slice(DELTA_MAGIC);
|
||||
out.push(DELTA_VERSION);
|
||||
out.extend_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// Buffer writes into 64 KiB chunks so serde_json's small token writes do not enter deflate individually.
|
||||
let encoder = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
|
||||
let mut buffered = BufWriter::with_capacity(64 * 1024, CountingWriter { inner: encoder, written: 0 });
|
||||
serde_json::to_writer(&mut buffered, wire).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
let counting = buffered.into_inner().map_err(|e| Error::Encode(e.into_error().to_string()))?;
|
||||
let written = counting.written;
|
||||
let len_u32 = u32::try_from(written).map_err(|_| Error::TooLarge(u32::MAX as usize))?;
|
||||
let mut out = counting.inner.finish().map_err(|e| Error::Encode(e.to_string()))?;
|
||||
if let Some(slot) = out.get_mut(5..9) {
|
||||
slot.copy_from_slice(&len_u32.to_le_bytes());
|
||||
}
|
||||
Ok((out, written))
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
//! Mirror field deltas and structural equality checks.
|
||||
//!
|
||||
//! `Paint` ignores `color_alpha` in `PartialEq`, and IEEE-754 equates `-0.0` with `0.0`.
|
||||
//! Float and paint fields therefore compare bit-for-bit or via serialized JSON so mirror
|
||||
//! encoding never drops data that legacy snapshots preserve.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use figcraft_doc::color::{BlendMode, Paint, PaintKind};
|
||||
use figcraft_doc::geom::Affine;
|
||||
use figcraft_doc::proto::{Interaction, Overflow, ScrollPosition};
|
||||
use figcraft_doc::{
|
||||
Annotation, AutoLayout, BoardItem, BoolOp, ChildLayout, CodeLink, CollectionId, Constraints, Corners, DevResource, DevStatus, Effect,
|
||||
ExportSetting, Guide, LayoutGrid, MaskType, Measurement, ModeId, Node, NodeKind, Region, Segment, Shared, StrokeProps, StyleRefs, VariableId,
|
||||
VectorNetwork, Vertex,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::encode::VectorInterner;
|
||||
use crate::Error;
|
||||
|
||||
/// Defines `FieldDelta`, mirror diffing and delta application from one field table so adding
|
||||
/// or editing a field keeps all three in lockstep.
|
||||
///
|
||||
/// New variants must be appended and gated behind a version or capability bump because older
|
||||
/// clients reject unknown variants during deserialization.
|
||||
macro_rules! delta_fields {
|
||||
(
|
||||
boxed: [ $( $bvar:ident ( $bty:ty ) => $bfield:ident via $beq:ident ),* $(,)? ],
|
||||
value: [ $( $vvar:ident ( $vty:ty ) => $vfield:ident via $veq:ident ),* $(,)? ]
|
||||
) => {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) enum FieldDelta {
|
||||
Kind(Box<NodeKind>),
|
||||
VectorRef(u32),
|
||||
$( $bvar(Box<$bty>), )*
|
||||
$( $vvar($vty), )*
|
||||
}
|
||||
|
||||
fn diff_table_fields(src: &Node, node: &Node, out: &mut Vec<FieldDelta>) {
|
||||
$(
|
||||
if !$beq(&node.$bfield, &src.$bfield) {
|
||||
out.push(FieldDelta::$bvar(Box::new(node.$bfield.clone())));
|
||||
}
|
||||
)*
|
||||
$(
|
||||
if !$veq(&node.$vfield, &src.$vfield) {
|
||||
out.push(FieldDelta::$vvar(node.$vfield.clone()));
|
||||
}
|
||||
)*
|
||||
}
|
||||
|
||||
pub(super) fn apply_field_delta(node: &mut Node, delta: FieldDelta, vectors: &[Shared<VectorNetwork>]) -> Result<(), Error> {
|
||||
match delta {
|
||||
FieldDelta::Kind(v) => node.kind = *v,
|
||||
FieldDelta::VectorRef(idx) => {
|
||||
let net = usize::try_from(idx)
|
||||
.ok()
|
||||
.and_then(|i| vectors.get(i))
|
||||
.ok_or_else(|| Error::Decode(format!("invalid vector ref {idx}")))?;
|
||||
node.kind = NodeKind::Vector { network: net.clone() };
|
||||
}
|
||||
$( FieldDelta::$bvar(v) => node.$bfield = *v, )*
|
||||
$( FieldDelta::$vvar(v) => node.$vfield = v, )*
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
delta_fields! {
|
||||
boxed: [
|
||||
Stroke(StrokeProps) => stroke via eq_exact,
|
||||
ChildLayout(ChildLayout) => child_layout via eq_exact,
|
||||
Styles(StyleRefs) => styles via eq_plain,
|
||||
],
|
||||
value: [
|
||||
Name(String) => name via eq_plain,
|
||||
Visible(bool) => visible via eq_plain,
|
||||
Locked(bool) => locked via eq_plain,
|
||||
Opacity(f32) => opacity via eq_f32,
|
||||
Blend(BlendMode) => blend via eq_plain,
|
||||
Transform(Affine) => transform via eq_affine,
|
||||
Width(f64) => width via eq_f64,
|
||||
Height(f64) => height via eq_f64,
|
||||
Fills(Vec<Paint>) => fills via eq_paint_vec,
|
||||
Strokes(Vec<Paint>) => strokes via eq_paint_vec,
|
||||
Effects(Vec<Effect>) => effects via eq_vec_exact,
|
||||
Corners(Corners) => corners via eq_exact,
|
||||
Constraints(Constraints) => constraints via eq_plain,
|
||||
Layout(Option<AutoLayout>) => layout via eq_opt_exact,
|
||||
Clip(bool) => clip via eq_plain,
|
||||
IsMask(bool) => is_mask via eq_plain,
|
||||
MaskType(MaskType) => mask_type via eq_plain,
|
||||
Grids(Vec<LayoutGrid>) => grids via eq_vec_exact,
|
||||
Guides(Vec<Guide>) => guides via eq_vec_exact,
|
||||
Exports(Vec<ExportSetting>) => exports via eq_vec_exact,
|
||||
Interactions(Vec<Interaction>) => interactions via eq_vec_exact,
|
||||
Overflow(Overflow) => overflow via eq_plain,
|
||||
ScrollPosition(ScrollPosition) => scroll_position via eq_exact,
|
||||
Bound(BTreeMap<String, VariableId>) => bound via eq_plain,
|
||||
VarModes(BTreeMap<CollectionId, ModeId>) => var_modes via eq_plain,
|
||||
ScaleFactor(f64) => scale_factor via eq_f64,
|
||||
BoolOp(Option<BoolOp>) => bool_op via eq_plain,
|
||||
ConstrainProportions(bool) => constrain_proportions via eq_plain,
|
||||
Exposed(bool) => exposed via eq_plain,
|
||||
DevStatus(DevStatus) => dev_status via eq_plain,
|
||||
DevChanged(bool) => dev_changed via eq_plain,
|
||||
DevNote(String) => dev_note via eq_plain,
|
||||
PropRefs(BTreeMap<String, String>) => prop_refs via eq_plain,
|
||||
PluginData(BTreeMap<String, String>) => plugin_data via eq_plain,
|
||||
Annotations(Vec<Annotation>) => annotations via eq_vec_exact,
|
||||
CodeLinks(Vec<CodeLink>) => code_links via eq_plain,
|
||||
DevResources(Vec<DevResource>) => dev_resources via eq_plain,
|
||||
Measurements(Vec<Measurement>) => measurements via eq_vec_exact,
|
||||
Board(Option<BoardItem>) => board via eq_opt_exact,
|
||||
]
|
||||
}
|
||||
|
||||
/// Fails to compile if a new field is added to `figcraft_doc::Node` without updating `delta_fields!`.
|
||||
#[allow(dead_code)]
|
||||
fn every_node_field_visited(n: &Node) {
|
||||
let Node {
|
||||
id: _,
|
||||
name: _,
|
||||
kind: _,
|
||||
parent: _,
|
||||
children: _,
|
||||
visible: _,
|
||||
locked: _,
|
||||
opacity: _,
|
||||
blend: _,
|
||||
transform: _,
|
||||
width: _,
|
||||
height: _,
|
||||
fills: _,
|
||||
strokes: _,
|
||||
stroke: _,
|
||||
effects: _,
|
||||
corners: _,
|
||||
constraints: _,
|
||||
layout: _,
|
||||
child_layout: _,
|
||||
clip: _,
|
||||
is_mask: _,
|
||||
mask_type: _,
|
||||
grids: _,
|
||||
guides: _,
|
||||
exports: _,
|
||||
interactions: _,
|
||||
overflow: _,
|
||||
scroll_position: _,
|
||||
styles: _,
|
||||
bound: _,
|
||||
var_modes: _,
|
||||
scale_factor: _,
|
||||
bool_op: _,
|
||||
constrain_proportions: _,
|
||||
source: _,
|
||||
exposed: _,
|
||||
dev_status: _,
|
||||
dev_changed: _,
|
||||
dev_note: _,
|
||||
overrides: _,
|
||||
prop_refs: _,
|
||||
plugin_data: _,
|
||||
annotations: _,
|
||||
code_links: _,
|
||||
dev_resources: _,
|
||||
measurements: _,
|
||||
board: _,
|
||||
} = n;
|
||||
}
|
||||
|
||||
pub(super) fn diff_mirror_fields(src: &Node, node: &Node, interner: &mut VectorInterner) -> Result<Vec<FieldDelta>, Error> {
|
||||
let mut deltas = Vec::new();
|
||||
if !exact_kind_eq(&node.kind, &src.kind) {
|
||||
match &node.kind {
|
||||
NodeKind::Vector { network } => deltas.push(FieldDelta::VectorRef(interner.intern(network)?)),
|
||||
other => deltas.push(FieldDelta::Kind(Box::new(other.clone()))),
|
||||
}
|
||||
}
|
||||
diff_table_fields(src, node, &mut deltas);
|
||||
Ok(deltas)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_plain<T: PartialEq>(a: &T, b: &T) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_f64(a: &f64, b: &f64) -> bool {
|
||||
a.to_bits() == b.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_f32(a: &f32, b: &f32) -> bool {
|
||||
a.to_bits() == b.to_bits()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn eq_affine(a: &Affine, b: &Affine) -> bool {
|
||||
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| x.to_bits() == y.to_bits())
|
||||
}
|
||||
|
||||
fn eq_json<T: Serialize + ?Sized>(a: &T, b: &T) -> bool {
|
||||
matches!((serde_json::to_vec(a), serde_json::to_vec(b)), (Ok(x), Ok(y)) if x == y)
|
||||
}
|
||||
|
||||
fn eq_exact<T: Serialize + PartialEq>(a: &T, b: &T) -> bool {
|
||||
a == b && eq_json(a, b)
|
||||
}
|
||||
|
||||
fn eq_vec_exact<T: Serialize + PartialEq>(a: &[T], b: &[T]) -> bool {
|
||||
(a.is_empty() && b.is_empty()) || (a == b && eq_json(a, b))
|
||||
}
|
||||
|
||||
fn eq_opt_exact<T: Serialize + PartialEq>(a: &Option<T>, b: &Option<T>) -> bool {
|
||||
match (a, b) {
|
||||
(None, None) => true,
|
||||
(Some(x), Some(y)) => x == y && eq_json(x, y),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn eq_paint(a: &Paint, b: &Paint) -> bool {
|
||||
if a.visible != b.visible || a.blend != b.blend || !eq_f32(&a.opacity, &b.opacity) || !eq_f32(&a.color_alpha, &b.color_alpha) {
|
||||
return false;
|
||||
}
|
||||
match (&a.kind, &b.kind) {
|
||||
(PaintKind::Solid { color: ca }, PaintKind::Solid { color: cb }) => {
|
||||
eq_f32(&ca.r, &cb.r) && eq_f32(&ca.g, &cb.g) && eq_f32(&ca.b, &cb.b) && eq_f32(&ca.a, &cb.a)
|
||||
}
|
||||
_ => a.kind == b.kind && eq_json(&a.kind, &b.kind),
|
||||
}
|
||||
}
|
||||
|
||||
fn eq_paint_vec(a: &[Paint], b: &[Paint]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| eq_paint(x, y))
|
||||
}
|
||||
|
||||
fn eq_vertex(a: &Vertex, b: &Vertex) -> bool {
|
||||
eq_f64(&a.x, &b.x) && eq_f64(&a.y, &b.y) && eq_f64(&a.radius, &b.radius) && a.mirror == b.mirror && a.cap == b.cap && a.join == b.join
|
||||
}
|
||||
|
||||
fn eq_segment(a: &Segment, b: &Segment) -> bool {
|
||||
a.a == b.a && a.b == b.b && eq_f64(&a.ta.0, &b.ta.0) && eq_f64(&a.ta.1, &b.ta.1) && eq_f64(&a.tb.0, &b.tb.0) && eq_f64(&a.tb.1, &b.tb.1)
|
||||
}
|
||||
|
||||
fn eq_region(a: &Region, b: &Region) -> bool {
|
||||
let fills_ok = match (&a.fills, &b.fills) {
|
||||
(None, None) => true,
|
||||
(Some(fa), Some(fb)) => eq_paint_vec(fa, fb),
|
||||
_ => false,
|
||||
};
|
||||
let space_ok = match (a.paint_space, b.paint_space) {
|
||||
(None, None) => true,
|
||||
(Some(pa), Some(pb)) => eq_f64(&pa.width, &pb.width) && eq_f64(&pa.height, &pb.height) && eq_affine(&pa.transform, &pb.transform),
|
||||
_ => false,
|
||||
};
|
||||
a.winding == b.winding && a.loops == b.loops && fills_ok && space_ok
|
||||
}
|
||||
|
||||
pub(super) fn exact_vector_network_eq(a: &VectorNetwork, b: &VectorNetwork) -> bool {
|
||||
a.vertices.len() == b.vertices.len()
|
||||
&& a.segments.len() == b.segments.len()
|
||||
&& a.regions.len() == b.regions.len()
|
||||
&& a.vertices.iter().zip(&b.vertices).all(|(x, y)| eq_vertex(x, y))
|
||||
&& a.segments.iter().zip(&b.segments).all(|(x, y)| eq_segment(x, y))
|
||||
&& a.regions.iter().zip(&b.regions).all(|(x, y)| eq_region(x, y))
|
||||
}
|
||||
|
||||
fn exact_kind_eq(a: &NodeKind, b: &NodeKind) -> bool {
|
||||
match (a, b) {
|
||||
(NodeKind::Frame, NodeKind::Frame)
|
||||
| (NodeKind::Group, NodeKind::Group)
|
||||
| (NodeKind::Rectangle, NodeKind::Rectangle)
|
||||
| (NodeKind::Line, NodeKind::Line) => true,
|
||||
(NodeKind::Vector { network: na }, NodeKind::Vector { network: nb }) => na.ptr_eq(nb) || exact_vector_network_eq(na, nb),
|
||||
(NodeKind::Text(ta), NodeKind::Text(tb)) => ta.ptr_eq(tb) || eq_exact(&**ta, &**tb),
|
||||
_ => eq_exact(a, b),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
//! Direct mirror-delta and deduplicated-vector snapshots (`CatchUp::DeltaSnapshot`).
|
||||
//!
|
||||
//! Used for clients whose hello announces `delta-snapshot` and `design-review`.
|
||||
//! Nodes are ordered topologically over `(parent, source)` edges so parents precede
|
||||
//! children and acyclic sources precede their mirrors. Mirrors diff field values
|
||||
//! structurally instead of trusting `Node::overrides`. Decoding streams records
|
||||
//! one at a time under inflated-byte, exact declared-length, node-count and
|
||||
//! materialized-memory budgets.
|
||||
|
||||
mod decode;
|
||||
mod encode;
|
||||
mod fields;
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use figcraft_doc::color::{Color, ColorProfile};
|
||||
use figcraft_doc::{
|
||||
AnnotationCategory, Ballots, BoardTimer, Comment, DesignReview, DevSnapshot, FileKind, ImagePreset, Libraries, Node, NodeId, VectorNetwork, Vote,
|
||||
VoteRecord,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Error;
|
||||
use fields::FieldDelta;
|
||||
|
||||
pub use decode::{decode_delta_snapshot, decode_delta_snapshot_with_budget};
|
||||
pub use encode::encode_delta_snapshot;
|
||||
|
||||
/// Wire header magic for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
|
||||
pub const DELTA_MAGIC: &[u8; 4] = b"FCDS";
|
||||
/// Wire format version for [`CatchUp::DeltaSnapshot`](crate::CatchUp::DeltaSnapshot).
|
||||
pub const DELTA_VERSION: u8 = 1;
|
||||
/// Fixed header size: 4-byte magic, 1-byte version, 4-byte little-endian uncompressed length.
|
||||
const HEADER_LEN: usize = 9;
|
||||
/// Default ceiling on estimated materialized bytes during decode.
|
||||
pub const DEFAULT_MAX_MATERIALIZED_BYTES: usize = 512 << 20;
|
||||
|
||||
/// Check the fixed header and declared uncompressed length in O(1).
|
||||
///
|
||||
/// Combined with [`decode_delta_snapshot_with_budget`] requiring `inflated.len() == declared`,
|
||||
/// this prevents a client from inflating past `max_bytes`.
|
||||
pub fn check_header_limit(bytes: &[u8], max_bytes: usize) -> Result<(), Error> {
|
||||
let declared = parse_header(bytes)?;
|
||||
if declared > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_header(bytes: &[u8]) -> Result<usize, Error> {
|
||||
let header = bytes.get(..HEADER_LEN).ok_or_else(|| Error::Decode("delta snapshot header is truncated".into()))?;
|
||||
if header.get(..4) != Some(DELTA_MAGIC.as_slice()) {
|
||||
return Err(Error::Decode("delta snapshot magic mismatch".into()));
|
||||
}
|
||||
let version = header.get(4).copied().ok_or_else(|| Error::Decode("delta snapshot version missing".into()))?;
|
||||
if version != DELTA_VERSION {
|
||||
return Err(Error::Decode(format!("unsupported delta snapshot version {version}")));
|
||||
}
|
||||
let len_slice = header.get(5..9).ok_or_else(|| Error::Decode("delta snapshot length missing".into()))?;
|
||||
let len_bytes: [u8; 4] = len_slice.try_into().map_err(|_| Error::Decode("delta snapshot length".into()))?;
|
||||
usize::try_from(u32::from_le_bytes(len_bytes)).map_err(|_| Error::TooLarge(usize::MAX))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(tag = "r", rename_all = "camelCase")]
|
||||
enum WireRecord {
|
||||
Full {
|
||||
pos: String,
|
||||
node: Box<Node>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
vref: Option<u32>,
|
||||
},
|
||||
Mirror(Box<MirrorWire>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct MirrorWire {
|
||||
id: NodeId,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
parent: Option<NodeId>,
|
||||
pos: String,
|
||||
source: NodeId,
|
||||
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
|
||||
overrides: BTreeSet<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
deltas: Vec<FieldDelta>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct WireImage {
|
||||
key: String,
|
||||
width: u32,
|
||||
height: u32,
|
||||
bytes: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct WireMeta {
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
kind: FileKind,
|
||||
#[serde(default)]
|
||||
styles: Vec<figcraft_doc::Style>,
|
||||
#[serde(default)]
|
||||
variables: figcraft_doc::Variables,
|
||||
#[serde(default)]
|
||||
current_page: Option<NodeId>,
|
||||
#[serde(default)]
|
||||
document_colors: Vec<Color>,
|
||||
#[serde(default)]
|
||||
comments: Vec<Comment>,
|
||||
#[serde(default)]
|
||||
libraries: Libraries,
|
||||
#[serde(default)]
|
||||
color_profile: ColorProfile,
|
||||
#[serde(default)]
|
||||
image_presets: Vec<ImagePreset>,
|
||||
#[serde(default)]
|
||||
design_review: DesignReview,
|
||||
#[serde(default)]
|
||||
annotation_categories: Option<Vec<AnnotationCategory>>,
|
||||
#[serde(default)]
|
||||
dev_snapshots: BTreeMap<NodeId, DevSnapshot>,
|
||||
#[serde(default)]
|
||||
timer: Option<BoardTimer>,
|
||||
#[serde(default)]
|
||||
vote: Option<Vote>,
|
||||
#[serde(default)]
|
||||
votes: Ballots,
|
||||
#[serde(default)]
|
||||
vote_history: Vec<VoteRecord>,
|
||||
#[serde(default)]
|
||||
images: Vec<WireImage>,
|
||||
}
|
||||
|
||||
/// Serialization envelope written in canonical order (`meta`, `vectors`, `records`).
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DeltaWireRef<'a> {
|
||||
meta: &'a WireMeta,
|
||||
#[serde(skip_serializing_if = "<[VectorNetwork]>::is_empty")]
|
||||
vectors: &'a [VectorNetwork],
|
||||
records: &'a [WireRecord],
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! Parity, exact-equality and hostile-input tests for `CatchUp::DeltaSnapshot`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{
|
||||
BoardTimer, Comment, DesignReview, DevSnapshot, Document, ImageData, ImagePreset, Libraries, NodeId, NodeKind, Segment, TextData, VectorNetwork,
|
||||
Vertex, Vote, VoteRecord,
|
||||
};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::delta_snapshot::{DELTA_MAGIC, DELTA_VERSION, decode_delta_snapshot, decode_delta_snapshot_with_budget, encode_delta_snapshot};
|
||||
use crate::message::{self, CatchUp, ClientMsg, ServerMsg};
|
||||
use crate::{Client, Error, Limits, Outgoing, Replica, Server};
|
||||
|
||||
pub(crate) const LEGACY_CLIENT_VERSION: &str = "0.18.1 signals hosting comments packed design-review branches";
|
||||
|
||||
/// Compare two documents via serialized JSON (excluding per-client `next_id`) so
|
||||
/// non-structural `PartialEq` cannot hide silent data loss.
|
||||
pub(crate) fn assert_docs_json_eq(left: &Document, right: &Document, context: &str) {
|
||||
let mut lj = serde_json::to_value(left).expect("serialize left doc");
|
||||
let mut rj = serde_json::to_value(right).expect("serialize right doc");
|
||||
if let Some(m) = lj.as_object_mut() {
|
||||
m.remove("next_id");
|
||||
}
|
||||
if let Some(m) = rj.as_object_mut() {
|
||||
m.remove("next_id");
|
||||
}
|
||||
assert_eq!(lj, rj, "{context}: serialized JSON mismatch");
|
||||
}
|
||||
|
||||
fn make_raw_delta_payload(json: &str, declared_override: Option<u32>) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(DELTA_MAGIC);
|
||||
out.push(DELTA_VERSION);
|
||||
let len = declared_override.unwrap_or(u32::try_from(json.len()).unwrap());
|
||||
out.extend_from_slice(&len.to_le_bytes());
|
||||
let mut z = flate2::write::DeflateEncoder::new(out, flate2::Compression::fast());
|
||||
z.write_all(json.as_bytes()).unwrap();
|
||||
z.finish().unwrap()
|
||||
}
|
||||
|
||||
pub(crate) fn sample_vector_icon(seed: usize, vertex_count: usize) -> VectorNetwork {
|
||||
let mut vertices = Vec::with_capacity(vertex_count);
|
||||
let mut segments = Vec::with_capacity(vertex_count);
|
||||
for i in 0..vertex_count {
|
||||
let a = (i as f64) * std::f64::consts::TAU / (vertex_count as f64) + (seed as f64) * 0.1;
|
||||
vertices.push(Vertex::new(16.0 + 12.0 * a.cos(), 16.0 + 12.0 * a.sin()));
|
||||
segments.push(Segment { a: i, b: (i + 1) % vertex_count, ta: (1.5, -0.5), tb: (-1.5, 0.5) });
|
||||
}
|
||||
VectorNetwork { vertices, segments, regions: Vec::new() }
|
||||
}
|
||||
|
||||
/// Build a document with cross-page instances (main component on page 2, instances on page 1),
|
||||
/// depth-2 mirror chains, repeated vector icons and stale empty `overrides` (#1819).
|
||||
pub(crate) fn design_system_doc(num_instances: usize) -> (Document, NodeId, Vec<NodeId>) {
|
||||
let mut doc = Document::new("DesignSystemDST");
|
||||
let page1 = doc.first_page().unwrap();
|
||||
let page2 = doc.add_page("Components");
|
||||
|
||||
let comp = doc
|
||||
.create(
|
||||
page2,
|
||||
NodeKind::Component { description: "Card".into(), props: BTreeMap::new(), prop_order: Vec::new() },
|
||||
"Card",
|
||||
0.0,
|
||||
0.0,
|
||||
320.0,
|
||||
200.0,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let icon_a = sample_vector_icon(1, 24);
|
||||
let icon_b = sample_vector_icon(2, 24);
|
||||
let mut main_children = Vec::new();
|
||||
for i in 0..6 {
|
||||
let kind = match i {
|
||||
0 | 1 => NodeKind::Text(TextData::new(format!("Title {i}")).into()),
|
||||
2 => NodeKind::Vector { network: icon_a.clone().into() },
|
||||
3 => NodeKind::Vector { network: icon_b.clone().into() },
|
||||
_ => NodeKind::Rectangle,
|
||||
};
|
||||
let cid = doc.create(comp, kind, &format!("Part {i}"), i as f64 * 24.0, 8.0, 32.0, 32.0).unwrap();
|
||||
if let Some(n) = doc.node_mut(cid) {
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(40, 100, (i * 30) as u8))];
|
||||
}
|
||||
main_children.push(cid);
|
||||
}
|
||||
|
||||
let main_snapshots: Vec<_> = main_children.iter().map(|id| doc.node(*id).unwrap().clone()).collect();
|
||||
let mut prev_inst_children: Option<Vec<NodeId>> = None;
|
||||
|
||||
for idx in 0..num_instances {
|
||||
let mut root = doc.node(comp).unwrap().clone();
|
||||
let inst_id = doc.alloc_id();
|
||||
root.id = inst_id;
|
||||
root.name = format!("Card #{idx}");
|
||||
root.kind = NodeKind::Instance { component: comp, props: BTreeMap::new() };
|
||||
root.children.clear();
|
||||
root.parent = None;
|
||||
root.source = Some(comp);
|
||||
root.transform = Affine::translate((idx as f64 * 340.0, 0.0));
|
||||
doc.insert(root, page1, None).unwrap();
|
||||
|
||||
let mut this_children = Vec::new();
|
||||
for (j, src) in main_snapshots.iter().enumerate() {
|
||||
let mut child = src.clone();
|
||||
child.id = doc.alloc_id();
|
||||
child.parent = None;
|
||||
child.children.clear();
|
||||
let chain_src = prev_inst_children.as_ref().filter(|_| idx % 3 == 2).map_or(src.id, |prev| prev[j]);
|
||||
child.source = Some(chain_src);
|
||||
|
||||
if j == 0 && idx % 2 == 0 {
|
||||
if let NodeKind::Text(t) = &mut child.kind {
|
||||
t.characters = format!("Overridden {idx}");
|
||||
}
|
||||
if idx % 4 != 0 {
|
||||
child.overrides.insert("characters".to_string());
|
||||
}
|
||||
}
|
||||
if j == 4 && idx % 5 == 0 {
|
||||
child.width = 99.0;
|
||||
child.transform = Affine::translate((12.0, 24.0));
|
||||
}
|
||||
let child_id = child.id;
|
||||
doc.insert(child, inst_id, None).unwrap();
|
||||
this_children.push(child_id);
|
||||
}
|
||||
prev_inst_children = Some(this_children);
|
||||
}
|
||||
|
||||
doc.take_dirty();
|
||||
(doc, comp, main_children)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_delta_preserves_paint_color_alpha_and_signed_zero() {
|
||||
let mut doc = Document::new("ExactEq");
|
||||
let page = doc.first_page().unwrap();
|
||||
let src = doc.create(page, NodeKind::Rectangle, "Src", 0.0, 0.0, 100.0, 50.0).unwrap();
|
||||
let mut src_paint = Paint::solid(Color::from_rgb8_const(20, 80, 200));
|
||||
src_paint.opacity = 0.5;
|
||||
src_paint.color_alpha = 0.5;
|
||||
if let Some(n) = doc.node_mut(src) {
|
||||
n.fills = vec![src_paint.clone()];
|
||||
n.strokes = vec![src_paint];
|
||||
}
|
||||
|
||||
let mut mirror = doc.node(src).unwrap().clone();
|
||||
mirror.id = doc.alloc_id();
|
||||
mirror.parent = None;
|
||||
mirror.source = Some(src);
|
||||
mirror.fills[0].color_alpha = 1.0;
|
||||
mirror.strokes[0].color_alpha = 0.25;
|
||||
mirror.width = -0.0;
|
||||
mirror.transform = Affine::translate((-0.0, 0.0));
|
||||
assert_eq!(doc.node(src).unwrap().fills, mirror.fills, "Paint PartialEq ignores color_alpha");
|
||||
doc.insert(mirror, page, None).unwrap();
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 16 << 20, Limits::default().max_nodes).unwrap();
|
||||
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
|
||||
assert_docs_json_eq(replica.document(), decoded.document(), "exact structural equality");
|
||||
assert_docs_json_eq(legacy.document(), decoded.document(), "legacy parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_hash_image_matches_legacy_join_parity() {
|
||||
let mut doc = Document::new("BadImage");
|
||||
let page = doc.first_page().unwrap();
|
||||
doc.create(page, NodeKind::Rectangle, "Box", 0.0, 0.0, 40.0, 40.0).unwrap();
|
||||
let bad_key = "0".repeat(64);
|
||||
doc.images.insert(bad_key.clone(), ImageData { bytes: Arc::new(b"not-matching-sha256".to_vec()), width: 10, height: 10 });
|
||||
doc.images.insert("svg_icon_1".into(), ImageData { bytes: Arc::new(b"valid-bytes".to_vec()), width: 16, height: 16 });
|
||||
doc.take_dirty();
|
||||
|
||||
let mut srv = Server::new(doc, "tok", Limits::default());
|
||||
let join_with = |srv: &mut Server, ver: Option<&str>| -> Client {
|
||||
let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "u", "#111") else { panic!() };
|
||||
if let Some(v) = ver {
|
||||
h.client_version = v.into();
|
||||
}
|
||||
let (id, outs) = srv.join(h).unwrap();
|
||||
let w = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
Client::join(w).unwrap()
|
||||
};
|
||||
|
||||
let legacy_client = join_with(&mut srv, Some(LEGACY_CLIENT_VERSION));
|
||||
let delta_client = join_with(&mut srv, None);
|
||||
assert!(!delta_client.document().images.contains_key(&bad_key));
|
||||
assert!(delta_client.document().images.contains_key("svg_icon_1"));
|
||||
assert_docs_json_eq(legacy_client.document(), delta_client.document(), "corrupt-image parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forged_declared_length_cannot_bypass_unpack_limit() {
|
||||
let huge_json = format!(
|
||||
r#"{{"meta":{{"name":"Bomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"{}","type":"page","width":0,"height":0}}}}]}}"#,
|
||||
"A".repeat(4 << 20)
|
||||
);
|
||||
let mut welcome = ServerMsg::Welcome {
|
||||
session: 1,
|
||||
client_id: 1,
|
||||
seq: 0,
|
||||
catch_up: CatchUp::DeltaSnapshot(make_raw_delta_payload(&huge_json, Some(10))),
|
||||
processed: message::Processed::default(),
|
||||
peers: Vec::new(),
|
||||
access: message::Access::Edit,
|
||||
secret: 1,
|
||||
};
|
||||
message::unpack(&mut welcome, 1 << 20).unwrap();
|
||||
let err = Client::join(welcome).unwrap_err();
|
||||
assert!(matches!(err, Error::TooLarge(10)), "forged length must abort at declared+1, got {err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirror_and_vref_amplification_bombs_are_rejected_within_memory_budget() {
|
||||
let big_text = "X".repeat(256 * 1024);
|
||||
let mut mirror_recs = String::from(
|
||||
r#"{"meta":{"name":"MirrorBomb"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},"#,
|
||||
);
|
||||
mirror_recs.push_str(&format!(
|
||||
r#"{{"r":"full","pos":"a0","node":{{"id":2,"name":"Big","parent":1,"type":"text","characters":"{big_text}","width":10,"height":10}}}}"#
|
||||
));
|
||||
for i in 3..2003u64 {
|
||||
mirror_recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#));
|
||||
}
|
||||
mirror_recs.push_str("]}");
|
||||
let err1 = decode_delta_snapshot(&make_raw_delta_payload(&mirror_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
|
||||
assert!(matches!(err1, Error::TooLarge(_)), "mirror bomb must fail TooLarge, got {err1:?}");
|
||||
|
||||
let net_json = serde_json::to_string(&sample_vector_icon(1, 20_000)).unwrap();
|
||||
let mut vref_recs = format!(
|
||||
r#"{{"meta":{{"name":"VrefBomb"}},"vectors":[{net_json}],"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}"#
|
||||
);
|
||||
for i in 2..3002u64 {
|
||||
vref_recs.push_str(&format!(
|
||||
r#",{{"r":"full","pos":"a{i:04}1","vref":0,"node":{{"id":{i},"name":"V","parent":1,"type":"vector","network":{{"vertices":[],"segments":[]}},"width":10,"height":10}}}}"#
|
||||
));
|
||||
}
|
||||
vref_recs.push_str("]}");
|
||||
let err2 = decode_delta_snapshot(&make_raw_delta_payload(&vref_recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
|
||||
assert!(matches!(err2, Error::TooLarge(_)), "vref bomb must fail TooLarge, got {err2:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_node_budget_and_hostile_inputs_are_rejected_cleanly() {
|
||||
let mut many =
|
||||
String::from(r#"{"meta":{"name":"Many"},"records":[{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}}"#);
|
||||
for i in 2..502u64 {
|
||||
many.push_str(&format!(
|
||||
r#",{{"r":"full","pos":"a{i:04}1","node":{{"id":{i},"name":"R","parent":1,"type":"rectangle","width":1,"height":1}}}}"#
|
||||
));
|
||||
}
|
||||
many.push_str("]}");
|
||||
let err = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&many, None), 16 << 20, 10, 64 << 20).unwrap_err();
|
||||
assert!(matches!(&err, Error::Invalid(msg) if msg.contains("10-node limit")), "got {err:?}");
|
||||
|
||||
let cyclic = r#"{"meta":{"name":"Evil"},"records":[
|
||||
{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
|
||||
{"r":"mirror","id":2,"parent":1,"pos":"a0","source":3},
|
||||
{"r":"mirror","id":3,"parent":1,"pos":"a1","source":2}
|
||||
]}"#;
|
||||
let self_cycle = r#"{"meta":{"name":"Self"},"records":[
|
||||
{"r":"full","pos":"a0","node":{"id":1,"name":"P","type":"page","width":0,"height":0}},
|
||||
{"r":"mirror","id":2,"parent":1,"pos":"a0","source":2}
|
||||
]}"#;
|
||||
assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(cyclic, None), 1 << 20, 100), Err(Error::Invalid(_))));
|
||||
assert!(matches!(decode_delta_snapshot(&make_raw_delta_payload(self_cycle, None), 1 << 20, 100), Err(Error::Invalid(_))));
|
||||
|
||||
for bad in [vec![], b"FCD".to_vec(), b"XXXX\x01\x00\x00\x00\x00".to_vec(), b"FCDS\x99\x00\x00\x00\x00".to_vec(), vec![0xFF; 64]] {
|
||||
assert!(decode_delta_snapshot(&bad, 1 << 20, 1000).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_metadata_and_design_review_roundtrip_matches_legacy_json() {
|
||||
let (mut doc, _, _) = design_system_doc(4);
|
||||
let page = doc.first_page().unwrap();
|
||||
doc.comments.push(Comment {
|
||||
id: 7,
|
||||
page,
|
||||
x: 10.0,
|
||||
y: 20.0,
|
||||
anchor: None,
|
||||
first: figcraft_doc::Message::new("Alice", "Check contrast", 1_700_000_000),
|
||||
resolved: false,
|
||||
replies: Vec::new(),
|
||||
read_by: None,
|
||||
});
|
||||
doc.dev_snapshots.insert(page, Arc::new(DevSnapshot { nodes: vec![Arc::new(doc.node(page).unwrap().clone())] }));
|
||||
doc.timer = Some(BoardTimer::Paused { left: 120_000 });
|
||||
let vote = Vote { per_person: 3, scope: Default::default(), ended: false, by: "Alice".into() };
|
||||
doc.vote = Some(vote.clone());
|
||||
doc.votes.entry("alice".into()).or_default().push(page);
|
||||
doc.vote_history.push(VoteRecord { vote, ballots: doc.votes.clone(), names: BTreeMap::new(), ended: 1_700_000_000 });
|
||||
doc.libraries = Arc::new(Libraries::default());
|
||||
doc.image_presets.push(ImagePreset { name: "Warm".into(), filters: Default::default() });
|
||||
doc.images.insert("logo_1".into(), ImageData { bytes: Arc::new(b"png-bytes".to_vec()), width: 32, height: 32 });
|
||||
doc.design_review = DesignReview { radii: vec![4.0; figcraft_doc::MAX_RADII + 10], ..DesignReview::default() };
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let legacy = Replica::from_snapshot(replica.snapshot().unwrap()).unwrap();
|
||||
let decoded = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 64 << 20, Limits::default().max_nodes).unwrap();
|
||||
assert_eq!(decoded.document().design_review.radii.len(), figcraft_doc::MAX_RADII);
|
||||
assert_docs_json_eq(legacy.document(), decoded.document(), "full metadata parity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_safely_roundtrips_cyclic_source_references_as_full_records() {
|
||||
let mut doc = Document::new("CyclicInMemory");
|
||||
let page = doc.first_page().unwrap();
|
||||
let a = doc.create(page, NodeKind::Rectangle, "A", 0.0, 0.0, 50.0, 50.0).unwrap();
|
||||
let b = doc.create(page, NodeKind::Rectangle, "B", 60.0, 0.0, 50.0, 50.0).unwrap();
|
||||
doc.node_mut(a).unwrap().source = Some(b);
|
||||
doc.node_mut(b).unwrap().source = Some(a);
|
||||
doc.take_dirty();
|
||||
|
||||
let replica = Replica::new(doc);
|
||||
let back = decode_delta_snapshot(&encode_delta_snapshot(&replica).unwrap(), 1 << 20, 100).unwrap();
|
||||
assert_docs_json_eq(replica.document(), back.document(), "cyclic source roundtrip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delta_snapshot_never_panics_when_truncated_or_bit_flipped() {
|
||||
let (doc, _, _) = design_system_doc(2);
|
||||
let valid = encode_delta_snapshot(&Replica::new(doc)).unwrap();
|
||||
// Truncations across header and compressed body.
|
||||
for cut in [0, 1, 4, 8, 9, 10, valid.len() / 2, valid.len() - 1] {
|
||||
assert!(decode_delta_snapshot(&valid[..cut], 16 << 20, 10_000).is_err());
|
||||
}
|
||||
// Single-bit flips across header and body must either error cleanly or produce a valid Replica.
|
||||
let stride = (valid.len() / 64).max(1);
|
||||
for idx in (0..valid.len()).step_by(stride) {
|
||||
let mut mutated = valid.clone();
|
||||
mutated[idx] ^= 0x80;
|
||||
let _ = decode_delta_snapshot(&mutated, 16 << 20, 10_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bound_map_amplification_and_oversized_metadata_are_rejected_by_budget() {
|
||||
// Source node with a large `bound` map mirrored 1,000 times must trip the memory budget.
|
||||
let mut bound_entries = Vec::with_capacity(200);
|
||||
for i in 0..200 {
|
||||
bound_entries.push(format!(r#""k{i:03}":"{}""#, "v".repeat(512)));
|
||||
}
|
||||
let bound_json = bound_entries.join(",");
|
||||
let mut recs = format!(
|
||||
r#"{{"meta":{{"name":"BoundBomb"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}},{{"r":"full","pos":"a0","node":{{"id":2,"name":"Src","parent":1,"type":"rectangle","width":10,"height":10,"bound":{{{bound_json}}}}}}}"#
|
||||
);
|
||||
for i in 3..1003u64 {
|
||||
recs.push_str(&format!(r#",{{"r":"mirror","id":{i},"parent":1,"pos":"a{i:04}1","source":2}}"#));
|
||||
}
|
||||
recs.push_str("]}");
|
||||
let err = decode_delta_snapshot(&make_raw_delta_payload(&recs, None), 16 << 20, Limits::default().max_nodes).unwrap_err();
|
||||
assert!(matches!(err, Error::TooLarge(_)), "bound-map amplification must fail TooLarge, got {err:?}");
|
||||
|
||||
// Oversized metadata (`name` of 2 MiB) under a 1 MiB materialized budget must fail TooLarge.
|
||||
let big_meta = format!(
|
||||
r#"{{"meta":{{"name":"{}"}},"records":[{{"r":"full","pos":"a0","node":{{"id":1,"name":"P","type":"page","width":0,"height":0}}}}]}}"#,
|
||||
"M".repeat(2 << 20)
|
||||
);
|
||||
let err2 = decode_delta_snapshot_with_budget(&make_raw_delta_payload(&big_meta, None), 16 << 20, 100, 1 << 20).unwrap_err();
|
||||
assert!(matches!(err2, Error::TooLarge(_)), "oversized metadata must fail TooLarge, got {err2:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_falls_back_to_legacy_snapshot_when_delta_exceeds_decode_budget() {
|
||||
// 2,000 mirrors of a 256 KiB text node exceed the client's 64x materialized ceiling:
|
||||
// the server must fall back to `CatchUp::Snapshot` so capable clients still join cleanly.
|
||||
let mut doc = Document::new("HighAmplificationHonest");
|
||||
let page = doc.first_page().unwrap();
|
||||
let src = doc.create(page, NodeKind::Text(TextData::new("T".repeat(256 * 1024)).into()), "Big", 0.0, 0.0, 100.0, 20.0).unwrap();
|
||||
let src_snap = doc.node(src).unwrap().clone();
|
||||
for _ in 0..2000 {
|
||||
let mut m = src_snap.clone();
|
||||
m.id = doc.alloc_id();
|
||||
m.parent = None;
|
||||
m.source = Some(src);
|
||||
doc.insert(m, page, None).unwrap();
|
||||
}
|
||||
doc.take_dirty();
|
||||
|
||||
assert!(matches!(encode_delta_snapshot(&Replica::new(doc.clone())), Err(Error::TooLarge(_))));
|
||||
let mut srv = Server::new(doc, "tok", Limits::default());
|
||||
let ClientMsg::Hello(h) = Client::hello("f", "tok", "u", "#222") else { panic!() };
|
||||
let (id, outs) = srv.join(h).unwrap();
|
||||
let welcome = outs
|
||||
.into_iter()
|
||||
.find_map(|o| match o {
|
||||
Outgoing::To(t, m @ ServerMsg::Welcome { .. }) if t == id => Some(m),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(matches!(welcome, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. }));
|
||||
}
|
||||
@@ -77,7 +77,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() {
|
||||
// A snapshot holding settings over the limits (an old file's) opens clamped to what fits:
|
||||
// the preset, grid and disabled rules exactly as saved, the lists to the limit.
|
||||
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
|
||||
assert!(clamped, "the settings needed clamping, and the caller is told");
|
||||
assert_eq!(left_out, 0, "nothing needed leaving out");
|
||||
let cfg = &r2.document().design_review;
|
||||
@@ -99,7 +99,7 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them
|
||||
assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}");
|
||||
// A snapshot with a longer list opens with the ones that fit, not without the settings.
|
||||
let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes;
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap();
|
||||
let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(snap).unwrap();
|
||||
assert!(clamped);
|
||||
assert_eq!(left_out, 0, "nothing needed leaving out");
|
||||
let cfg = &r2.document().design_review;
|
||||
@@ -232,9 +232,9 @@ fn snapshots_rebuild_the_same_state() {
|
||||
b.styles.push(style("s"));
|
||||
let r = diff(&a, &b).unwrap().replica;
|
||||
let snap = r.snapshot().unwrap();
|
||||
let back = Replica::from_snapshot(&snap).unwrap();
|
||||
let back = Replica::from_snapshot(snap).unwrap();
|
||||
assert_eq!(back, r);
|
||||
assert!(Replica::from_snapshot(&[]).is_err(), "a snapshot needs a page");
|
||||
assert!(Replica::from_snapshot(Vec::new()).is_err(), "a snapshot needs a page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -290,27 +290,61 @@ fn image_of(key: &str, value: &Json) -> Result<ImageData, Error> {
|
||||
image_within(key, value, ImageData::MAX_BYTES)
|
||||
}
|
||||
|
||||
/// [`image_of`] with `max_bytes` for the decoded size.
|
||||
pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
/// Validate raw image bytes and dimensions under the same security rules as [`image_of`] (#1086).
|
||||
pub(crate) fn validate_image_raw_within(key: &str, width: u32, height: u32, bytes: Vec<u8>, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
let v: ImageValue = value.read("image")?;
|
||||
if v.width > MAX_IMAGE_SIDE || v.height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {}×{} passes the {} a side may be", v.width, v.height, MAX_IMAGE_SIDE)));
|
||||
if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
|
||||
}
|
||||
let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
|
||||
if u64::try_from(v.bytes.len()).unwrap_or(u64::MAX) > max_encoded {
|
||||
return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
|
||||
}
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(v.bytes.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
|
||||
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > max_bytes {
|
||||
return Err(Error::Invalid(format!("image: {} bytes pass the {max_bytes} an image may be", bytes.len())));
|
||||
}
|
||||
if ImageData::claims_content_hash(key) && key != sha256_hex(&bytes) {
|
||||
return Err(Error::Invalid(format!("image: the bytes aren't what their key {key} hashes to")));
|
||||
}
|
||||
Ok(ImageData { bytes: Arc::new(bytes), width: v.width, height: v.height })
|
||||
Ok(ImageData { bytes: Arc::new(bytes), width, height })
|
||||
}
|
||||
|
||||
/// Validate base64-encoded image bytes and dimensions under [`ImageData::MAX_BYTES`].
|
||||
pub(crate) fn validate_image_base64(key: &str, width: u32, height: u32, encoded: &str) -> Result<ImageData, Error> {
|
||||
validate_image_base64_within(key, width, height, encoded, ImageData::MAX_BYTES)
|
||||
}
|
||||
|
||||
fn validate_image_base64_within(key: &str, width: u32, height: u32, encoded: &str, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
if width > MAX_IMAGE_SIDE || height > MAX_IMAGE_SIDE {
|
||||
return Err(Error::Invalid(format!("image: {width}×{height} passes the {MAX_IMAGE_SIDE} a side may be")));
|
||||
}
|
||||
let max_encoded = (max_bytes / 3).saturating_mul(4).saturating_add(4);
|
||||
if u64::try_from(encoded.len()).unwrap_or(u64::MAX) > max_encoded {
|
||||
return Err(Error::Invalid(format!("image: base64 text longer than {max_encoded} bytes for {max_bytes} of bytes")));
|
||||
}
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(encoded.as_bytes()).map_err(|e| Error::Invalid(format!("image: {e}")))?;
|
||||
validate_image_raw_within(key, width, height, bytes, max_bytes)
|
||||
}
|
||||
|
||||
/// Clamp oversized review settings in place (matches [`clamp_snapshot_design_review`]).
|
||||
pub(crate) fn clamp_design_review_config(config: &mut figcraft_doc::DesignReview) -> bool {
|
||||
if config.over_limits().is_empty() {
|
||||
return false;
|
||||
}
|
||||
config.radii.truncate(figcraft_doc::MAX_RADII);
|
||||
config.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
|
||||
config.disabled.truncate(figcraft_doc::MAX_DISABLED);
|
||||
true
|
||||
}
|
||||
|
||||
/// [`image_of`] with `max_bytes` for the decoded size.
|
||||
pub(crate) fn image_within(key: &str, value: &Json, max_bytes: u64) -> Result<ImageData, Error> {
|
||||
if !ImageData::is_valid_key(key) {
|
||||
return Err(Error::Invalid(format!("image: {key:?} can't name an image (1–128 letters, digits, - or _)")));
|
||||
}
|
||||
let v: ImageValue = value.read("image")?;
|
||||
validate_image_base64_within(key, v.width, v.height, &v.bytes, max_bytes)
|
||||
}
|
||||
|
||||
macro_rules! doc_scalars {
|
||||
@@ -413,17 +447,12 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec<Change>) -> bool {
|
||||
let mut clamped_any = false;
|
||||
for c in changes {
|
||||
if let Change::SetDoc { prop: DocProp::DesignReview, value } = c
|
||||
&& let Ok(config) = value.read::<figcraft_doc::DesignReview>("design review")
|
||||
&& !config.over_limits().is_empty()
|
||||
&& let Ok(mut clamped) = value.read::<figcraft_doc::DesignReview>("design review")
|
||||
&& clamp_design_review_config(&mut clamped)
|
||||
&& let Ok(v) = Json::of(&clamped)
|
||||
{
|
||||
let mut clamped = config;
|
||||
clamped.radii.truncate(figcraft_doc::MAX_RADII);
|
||||
clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS);
|
||||
clamped.disabled.truncate(figcraft_doc::MAX_DISABLED);
|
||||
if let Ok(v) = Json::of(&clamped) {
|
||||
*value = v;
|
||||
clamped_any = true;
|
||||
}
|
||||
*value = v;
|
||||
clamped_any = true;
|
||||
}
|
||||
}
|
||||
clamped_any
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
//! Fault-injection simulation over many seeds: asymmetric partitions (some clients cut off while
|
||||
//! the rest push the server past its log), connections dropped with batches in flight, offline
|
||||
//! edits queued and sent on reconnect, one-way link stalls, and per-user undo and redo mixed with
|
||||
//! edits to layers, styles, variables, comments, component instances and pages. Every seed must
|
||||
//! catch up all three ways (missed batches from the log, a compressed snapshot, a plain snapshot
|
||||
//! for an older app) and end converged, valid, with sequence numbers that never go back, deleted
|
||||
//! ids that aren't live, and no undo that reverted someone else's write.
|
||||
//!
|
||||
//! One seed: `FIGCRAFT_DST_SEED=7 cargo test -p figcraft-collab dst_fault`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use figcraft_color::{Color, Paint};
|
||||
use figcraft_doc::{Collection, Comment, Document, Message, Mode, NodeId, NodeKind, TextData, Variable, VariableType, VariableValue};
|
||||
use figcraft_geom::Affine;
|
||||
|
||||
use crate::delta_snapshot_tests::LEGACY_CLIENT_VERSION;
|
||||
use crate::server::MAX_DELETED;
|
||||
use crate::sim::{Rng, Sim};
|
||||
use crate::sim_tests::{base, random_edit};
|
||||
use crate::{Limits, NoRecompute};
|
||||
|
||||
const CLIENTS: usize = 4;
|
||||
/// Reconnects with an older app that reads only plain snapshots.
|
||||
const LEGACY: usize = 2;
|
||||
|
||||
/// The shared file: frames of rectangles, a component with two instances on another page, a
|
||||
/// variable collection with two modes, and a comment.
|
||||
fn fixture() -> Document {
|
||||
let mut d = base();
|
||||
let first = d.first_page().unwrap();
|
||||
let parts = d.add_page("Components");
|
||||
let comp = d
|
||||
.create(
|
||||
parts,
|
||||
NodeKind::Component { description: "Button".into(), props: BTreeMap::new(), prop_order: Vec::new() },
|
||||
"Button",
|
||||
0.0,
|
||||
0.0,
|
||||
120.0,
|
||||
40.0,
|
||||
)
|
||||
.unwrap();
|
||||
d.create(comp, NodeKind::Rectangle, "Fill", 0.0, 0.0, 120.0, 40.0).unwrap();
|
||||
d.create(comp, NodeKind::Text(TextData::new("Label".to_string()).into()), "Label", 8.0, 8.0, 100.0, 24.0).unwrap();
|
||||
for i in 0..2 {
|
||||
instantiate(&mut d, comp, first, i as f64 * 150.0).unwrap();
|
||||
}
|
||||
let cid = d.new_collection_id();
|
||||
d.variables.collections.push(Collection {
|
||||
id: cid.clone(),
|
||||
name: "Theme".into(),
|
||||
modes: vec![Mode { id: format!("{cid}/light"), name: "Light".into() }, Mode { id: format!("{cid}/dark"), name: "Dark".into() }],
|
||||
extends: None,
|
||||
});
|
||||
add_variable(&mut d, 4);
|
||||
let k = d.new_comment_id();
|
||||
d.comments.push(comment(k, first, "Check the spacing"));
|
||||
d.take_dirty();
|
||||
d
|
||||
}
|
||||
|
||||
/// An instance of `comp` under `parent`: a root following the component and one mirror per child.
|
||||
fn instantiate(doc: &mut Document, comp: NodeId, parent: NodeId, x: f64) -> Option<NodeId> {
|
||||
let main = doc.node(comp)?.clone();
|
||||
let inst = doc.alloc_id();
|
||||
let mut root = main.clone();
|
||||
root.id = inst;
|
||||
root.name = format!("{} instance", main.name);
|
||||
root.kind = NodeKind::Instance { component: comp, props: BTreeMap::new() };
|
||||
root.children.clear();
|
||||
root.parent = None;
|
||||
root.source = Some(comp);
|
||||
root.transform = Affine::translate((x, 300.0));
|
||||
doc.insert(root, parent, None).ok()?;
|
||||
for c in main.children {
|
||||
let mut mirror = doc.node(c)?.clone();
|
||||
mirror.id = doc.alloc_id();
|
||||
mirror.parent = None;
|
||||
mirror.children.clear();
|
||||
mirror.source = Some(c);
|
||||
mirror.overrides.clear();
|
||||
doc.insert(mirror, inst, None).ok()?;
|
||||
}
|
||||
Some(inst)
|
||||
}
|
||||
|
||||
fn comment(id: u64, page: NodeId, text: &str) -> Comment {
|
||||
Comment { id, page, x: 10.0, y: 20.0, anchor: None, first: Message::new("DST", text, 0), resolved: false, replies: Vec::new(), read_by: None }
|
||||
}
|
||||
|
||||
/// A number variable in the first collection, `value` in every mode.
|
||||
fn add_variable(doc: &mut Document, value: u32) {
|
||||
let Some(c) = doc.variables.collections.first() else { return };
|
||||
let (cid, values) = (c.id.clone(), c.modes.iter().map(|m| (m.id.clone(), VariableValue::Number(f64::from(value)))).collect());
|
||||
let id = doc.new_variable_id();
|
||||
doc.variables.variables.push(Variable {
|
||||
id,
|
||||
name: format!("space/{value}"),
|
||||
collection: cid,
|
||||
kind: VariableType::Number,
|
||||
values,
|
||||
description: String::new(),
|
||||
scopes: None,
|
||||
hidden_from_publishing: false,
|
||||
extends: None,
|
||||
overrides: Default::default(),
|
||||
code_syntax: Default::default(),
|
||||
});
|
||||
}
|
||||
|
||||
fn of_kind(doc: &Document, f: impl Fn(&NodeKind) -> bool) -> Vec<NodeId> {
|
||||
doc.nodes().filter(|n| f(&n.kind)).map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// One random edit: layers, styles and pages ([`random_edit`]) half the time, else variables,
|
||||
/// comments, instances (overrides, new instances), main components or page names.
|
||||
fn fault_edit(doc: &mut Document, rng: &mut Rng) {
|
||||
match rng.below(12) {
|
||||
0..=5 => random_edit(doc, rng, &NoRecompute),
|
||||
6 => match rng.below(4) {
|
||||
0 => add_variable(doc, rng.below(100) as u32),
|
||||
1 => {
|
||||
let n = doc.variables.variables.len();
|
||||
if let Some(v) = doc.variables.variables.get_mut(rng.below(n)) {
|
||||
let mode = v.values.keys().nth(rng.below(v.values.len())).cloned();
|
||||
if let Some(m) = mode {
|
||||
v.values.insert(m, VariableValue::Number(rng.below(64) as f64));
|
||||
}
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
let n = doc.variables.variables.len();
|
||||
if let Some(v) = doc.variables.variables.get_mut(rng.below(n)) {
|
||||
v.name = format!("renamed/{}", rng.below(100));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if doc.variables.variables.len() > 1 {
|
||||
let i = rng.below(doc.variables.variables.len());
|
||||
doc.variables.variables.remove(i);
|
||||
}
|
||||
}
|
||||
},
|
||||
7 => {
|
||||
let n = doc.comments.len();
|
||||
match rng.below(4) {
|
||||
0 => {
|
||||
let page = doc.pages[rng.below(doc.pages.len())];
|
||||
let k = doc.new_comment_id();
|
||||
doc.comments.push(comment(k, page, &format!("Note {}", rng.below(100))));
|
||||
}
|
||||
1 => {
|
||||
if let Some(c) = doc.comments.get_mut(rng.below(n)) {
|
||||
c.resolved = !c.resolved;
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
if let Some(c) = doc.comments.get_mut(rng.below(n)) {
|
||||
c.replies.push(Message::new("DST", format!("Reply {}", rng.below(100)), 0));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if n > 0 {
|
||||
doc.comments.remove(rng.below(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
8 => {
|
||||
// An override on an instance's mirror, or the instance moved or renamed.
|
||||
let mirrors: Vec<NodeId> =
|
||||
doc.nodes().filter(|n| n.source.is_some() && !matches!(n.kind, NodeKind::Instance { .. })).map(|n| n.id).collect();
|
||||
let instances = of_kind(doc, |k| matches!(k, NodeKind::Instance { .. }));
|
||||
if rng.chance(0.5)
|
||||
&& let Some(n) = rng.pick(&mirrors).copied().and_then(|m| doc.node_mut(m))
|
||||
{
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(0, rng.below(256) as u8, 200))];
|
||||
n.overrides.insert("fills".to_string());
|
||||
} else if let Some(n) = rng.pick(&instances).copied().and_then(|m| doc.node_mut(m)) {
|
||||
n.transform = Affine::translate((rng.below(600) as f64, 300.0));
|
||||
n.name = format!("Button {}", rng.below(50));
|
||||
}
|
||||
}
|
||||
9 => {
|
||||
let comps = of_kind(doc, |k| matches!(k, NodeKind::Component { .. }));
|
||||
if let (Some(&comp), Some(&page)) = (rng.pick(&comps), doc.pages.first()) {
|
||||
let x = rng.below(800) as f64;
|
||||
let _ = instantiate(doc, comp, page, x);
|
||||
}
|
||||
}
|
||||
10 => {
|
||||
// The main component changes: what instances follow.
|
||||
let comps = of_kind(doc, |k| matches!(k, NodeKind::Component { .. }));
|
||||
let parts: Vec<NodeId> = comps.iter().filter_map(|c| doc.node(*c)).flat_map(|n| n.children.clone()).collect();
|
||||
if let Some(n) = rng.pick(&parts).copied().and_then(|p| doc.node_mut(p)) {
|
||||
n.fills = vec![Paint::solid(Color::from_rgb8_const(rng.below(256) as u8, 120, 0))];
|
||||
n.opacity = rng.below(11) as f32 / 10.0;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let pages = doc.pages.clone();
|
||||
if let Some(n) = rng.pick(&pages).copied().and_then(|p| doc.node_mut(p)) {
|
||||
n.name = format!("Page {}", rng.below(100));
|
||||
} else {
|
||||
doc.add_page("Extra");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sequence numbers seen so far: the server's and each client's never go back.
|
||||
struct Watch {
|
||||
seed: u64,
|
||||
server: u64,
|
||||
clients: Vec<u64>,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
fn check(&mut self, sim: &Sim) {
|
||||
let seed = self.seed;
|
||||
assert!(sim.server.seq() >= self.server, "seed {seed}: the server went back from {} to {}", self.server, sim.server.seq());
|
||||
self.server = sim.server.seq();
|
||||
for (i, c) in sim.clients().iter().enumerate() {
|
||||
assert!(c.seq() >= self.clients[i], "seed {seed}: client {i} went back from {} to {}", self.clients[i], c.seq());
|
||||
assert!(c.seq() <= self.server, "seed {seed}: client {i} at {} is ahead of the server at {}", c.seq(), self.server);
|
||||
self.clients[i] = c.seq();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deliver up to `n` messages, checking sequence numbers after each.
|
||||
fn pump(sim: &mut Sim, w: &mut Watch, n: usize) {
|
||||
for _ in 0..n {
|
||||
if !sim.step(&NoRecompute).unwrap() {
|
||||
break;
|
||||
}
|
||||
w.check(sim);
|
||||
}
|
||||
}
|
||||
|
||||
/// Deliver everything in flight.
|
||||
fn quiesce(sim: &mut Sim, w: &mut Watch) {
|
||||
pump(sim, w, 1_000_000);
|
||||
sim.settle(&NoRecompute, 0).unwrap();
|
||||
}
|
||||
|
||||
fn edit(sim: &mut Sim, i: usize) -> bool {
|
||||
let mut doc = sim.document(i).unwrap().clone();
|
||||
let mut rng = Rng::new(sim.rng().next_u64());
|
||||
fault_edit(&mut doc, &mut rng);
|
||||
sim.edit(i, &doc).unwrap()
|
||||
}
|
||||
|
||||
/// An edit that always makes a batch (queued, offline): the first page renamed.
|
||||
fn sure_edit(sim: &mut Sim, i: usize, tag: &str) {
|
||||
let mut doc = sim.document(i).unwrap().clone();
|
||||
let page = doc.pages[0];
|
||||
doc.node_mut(page).unwrap().name = format!("{tag} by {i}");
|
||||
let queued = sim.clients()[i].pending();
|
||||
sim.edit(i, &doc).unwrap();
|
||||
assert!(sim.clients()[i].pending() > queued, "{tag}: no batch");
|
||||
}
|
||||
|
||||
/// Client `i` edits, undoes, redoes, drops or regains its connection, or its link stalls one way.
|
||||
fn act(sim: &mut Sim, i: usize, faults: bool) {
|
||||
match sim.rng().below(12) {
|
||||
0 | 1 => {
|
||||
sim.undo(i, &NoRecompute).unwrap();
|
||||
}
|
||||
2 => {
|
||||
sim.redo(i, &NoRecompute).unwrap();
|
||||
}
|
||||
3 if faults => {
|
||||
if sim.is_online(i) {
|
||||
sim.disconnect(i).unwrap();
|
||||
} else {
|
||||
sim.reconnect(i).unwrap();
|
||||
}
|
||||
}
|
||||
4 if faults => {
|
||||
let (up, ticks) = (sim.rng().chance(0.5), 1 + sim.rng().below(40) as u64);
|
||||
sim.stall(i, up, ticks);
|
||||
}
|
||||
_ => {
|
||||
edit(sim, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Online clients in `actors` edit until the server is `by` batches further (refused and empty
|
||||
/// edits don't count), delivering everything after each edit when `settle`.
|
||||
fn advance(sim: &mut Sim, w: &mut Watch, actors: &[usize], by: u64, settle: bool) {
|
||||
let target = sim.server.seq() + by;
|
||||
let mut tries = 0;
|
||||
while sim.server.seq() < target {
|
||||
tries += 1;
|
||||
assert!(tries < 2_000, "seed {}: the server stuck at {} (target {target})", w.seed, sim.server.seq());
|
||||
let i = actors[sim.rng().below(actors.len())];
|
||||
edit(sim, i);
|
||||
if settle {
|
||||
quiesce(sim, w);
|
||||
} else {
|
||||
let n = sim.rng().below(4);
|
||||
pump(sim, w, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop client `i`'s connection with its last edit possibly still in flight, then edit (and maybe
|
||||
/// undo) offline: the queue must hold work for the reconnect.
|
||||
fn cut_off(sim: &mut Sim, w: &mut Watch, i: usize, tag: &str) {
|
||||
edit(sim, i);
|
||||
let n = sim.rng().below(3);
|
||||
pump(sim, w, n);
|
||||
sim.disconnect(i).unwrap();
|
||||
sure_edit(sim, i, tag);
|
||||
for _ in 0..sim.rng().below(4) {
|
||||
edit(sim, i);
|
||||
}
|
||||
if sim.rng().chance(0.5) {
|
||||
sim.undo(i, &NoRecompute).unwrap();
|
||||
if sim.rng().chance(0.5) {
|
||||
sim.redo(i, &NoRecompute).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What must hold whenever nothing is in flight and everyone is back.
|
||||
fn check_quiet(sim: &Sim, seed: u64, when: &str) {
|
||||
if let Err(e) = sim.converged() {
|
||||
panic!("seed {seed} {when}: {e}");
|
||||
}
|
||||
let doc = sim.server.document();
|
||||
assert!(doc.validate().is_empty(), "seed {seed} {when}: {:?}", doc.validate());
|
||||
for (i, c) in sim.clients().iter().enumerate() {
|
||||
assert!(c.document().validate().is_empty(), "seed {seed} {when}: client {i}: {:?}", c.document().validate());
|
||||
}
|
||||
assert!(sim.violations.is_empty(), "seed {seed} {when}: {:?}", sim.violations);
|
||||
let deleted = sim.server.state().unwrap().deleted;
|
||||
assert!(deleted.len() <= MAX_DELETED, "seed {seed} {when}: {} deleted ids remembered", deleted.len());
|
||||
let live: Vec<_> = deleted.iter().filter(|id| doc.contains(**id)).collect();
|
||||
assert!(live.is_empty(), "seed {seed} {when}: ids remembered as deleted are in the document: {live:?}");
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
undos: usize,
|
||||
log_catch_ups: usize,
|
||||
delta_snapshots: usize,
|
||||
plain_snapshots: usize,
|
||||
}
|
||||
|
||||
fn run_seed(seed: u64) -> Outcome {
|
||||
let retention = 4 + (seed % 3) as usize;
|
||||
let limits = Limits { max_log_batches: retention, ..Limits::default() };
|
||||
let mut sim = Sim::with_limits(fixture(), CLIENTS, seed, 1 + seed % 12, limits).unwrap();
|
||||
sim.set_version(LEGACY, LEGACY_CLIENT_VERSION);
|
||||
let mut w = Watch { seed, server: 0, clients: vec![0; CLIENTS] };
|
||||
|
||||
// Everyone works at once for a while.
|
||||
for _ in 0..20 {
|
||||
let i = sim.rng().below(CLIENTS);
|
||||
act(&mut sim, i, false);
|
||||
let n = sim.rng().below(4);
|
||||
pump(&mut sim, &mut w, n);
|
||||
}
|
||||
quiesce(&mut sim, &mut w);
|
||||
check_quiet(&sim, seed, "after warm-up");
|
||||
|
||||
// A short partition: client 1 misses a batch or two, still in the log.
|
||||
let before = sim.log_catch_ups;
|
||||
cut_off(&mut sim, &mut w, 1, "short");
|
||||
quiesce(&mut sim, &mut w);
|
||||
advance(&mut sim, &mut w, &[0, 3], 1, true);
|
||||
assert!(sim.clients()[1].pending() > 0, "seed {seed}: client 1 queued nothing offline");
|
||||
sim.reconnect(1).unwrap();
|
||||
assert!(sim.log_catch_ups > before, "seed {seed}: the short absence wasn't caught up from the log");
|
||||
quiesce(&mut sim, &mut w);
|
||||
check_quiet(&sim, seed, "after the short partition");
|
||||
|
||||
// An asymmetric partition: the older app and a current one are cut off while the other two
|
||||
// push the server well past what its log keeps, one of them stalling on the way.
|
||||
let (plain, delta) = (sim.plain_snapshots, sim.delta_snapshots);
|
||||
cut_off(&mut sim, &mut w, LEGACY, "long");
|
||||
cut_off(&mut sim, &mut w, 3, "long");
|
||||
let ticks = 5 + sim.rng().below(30) as u64;
|
||||
let up = sim.rng().chance(0.5);
|
||||
sim.stall(0, up, ticks);
|
||||
let past = retention as u64 + 2 + sim.rng().below(3) as u64;
|
||||
advance(&mut sim, &mut w, &[0, 1], past, false);
|
||||
for _ in 0..10 {
|
||||
let i = sim.rng().below(2);
|
||||
act(&mut sim, i, false);
|
||||
let n = sim.rng().below(3);
|
||||
pump(&mut sim, &mut w, n);
|
||||
}
|
||||
for i in [LEGACY, 3] {
|
||||
assert!(sim.clients()[i].pending() > 0, "seed {seed}: client {i} queued nothing offline");
|
||||
}
|
||||
// They come back while the others' batches are still in flight.
|
||||
sim.reconnect(LEGACY).unwrap();
|
||||
sim.reconnect(3).unwrap();
|
||||
assert!(sim.plain_snapshots > plain, "seed {seed}: the older app didn't catch up with a plain snapshot");
|
||||
assert!(sim.delta_snapshots > delta, "seed {seed}: the current app didn't catch up with a compressed snapshot");
|
||||
quiesce(&mut sim, &mut w);
|
||||
check_quiet(&sim, seed, "after the long partition");
|
||||
|
||||
// Everyone at once with every fault: drops, reconnects, stalls, undo and redo.
|
||||
for _ in 0..60 {
|
||||
let i = sim.rng().below(CLIENTS);
|
||||
act(&mut sim, i, true);
|
||||
let n = sim.rng().below(4);
|
||||
pump(&mut sim, &mut w, n);
|
||||
}
|
||||
for i in 0..CLIENTS {
|
||||
sim.reconnect(i).unwrap();
|
||||
}
|
||||
quiesce(&mut sim, &mut w);
|
||||
check_quiet(&sim, seed, "at the end");
|
||||
assert!(sim.undos > 0, "seed {seed}: no undo or redo was accepted");
|
||||
Outcome { undos: sim.undos, log_catch_ups: sim.log_catch_ups, delta_snapshots: sim.delta_snapshots, plain_snapshots: sim.plain_snapshots }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fixture_and_every_kind_of_edit_stay_valid() {
|
||||
let doc = fixture();
|
||||
assert!(doc.validate().is_empty(), "{:?}", doc.validate());
|
||||
assert_eq!(of_kind(&doc, |k| matches!(k, NodeKind::Instance { .. })).len(), 2);
|
||||
let mut rng = Rng::new(3);
|
||||
let mut d = doc.clone();
|
||||
for step in 0..500 {
|
||||
fault_edit(&mut d, &mut rng);
|
||||
assert!(d.validate().is_empty(), "step {step}: {:?}", d.validate());
|
||||
}
|
||||
assert!(d.variables.variables.len() + d.comments.len() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dst_fault_injection_converges_on_every_seed() {
|
||||
let seeds: Vec<u64> = match std::env::var("FIGCRAFT_DST_SEED").ok().and_then(|s| s.parse().ok()) {
|
||||
Some(one) => vec![one],
|
||||
None => (0..32).collect(),
|
||||
};
|
||||
let mut total = Outcome { undos: 0, log_catch_ups: 0, delta_snapshots: 0, plain_snapshots: 0 };
|
||||
for seed in seeds {
|
||||
let o = run_seed(seed);
|
||||
total.undos += o.undos;
|
||||
total.log_catch_ups += o.log_catch_ups;
|
||||
total.delta_snapshots += o.delta_snapshots;
|
||||
total.plain_snapshots += o.plain_snapshots;
|
||||
}
|
||||
assert!(total.undos > 0 && total.log_catch_ups > 0 && total.delta_snapshots > 0 && total.plain_snapshots > 0);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Room kept ahead in a web page's heap while a large file is read (#2041).
|
||||
//!
|
||||
//! The allocator Rust links on `wasm32-unknown-unknown` (dlmalloc) asks the page for more memory
|
||||
//! one 64 KiB page at a time whenever it runs out, and the browser changes the protection of the
|
||||
//! whole memory at every grow. Joining a 121k-layer file grew the heap by about 1.5 GB in about
|
||||
//! 20,000 grows; their total cost rises with the square of the heap size and took minutes on
|
||||
//! Windows. Memory the allocator got is reused once freed and never handed back, so allocating one
|
||||
//! large block and freeing it at once leaves that much room for what follows, for one grow.
|
||||
//! [`keep_ahead`] does that whenever the memory grew since its last call: half the heap again, at
|
||||
//! most [`MAX_STEP`], so the heap grows in a few dozen steps.
|
||||
//!
|
||||
//! It acts only while a snapshot is read ([`reading`]): the hooks sit in code every live edit runs
|
||||
//! too (applying a batch, reading a property value), and an edit never reserves memory. Off the web
|
||||
//! it does nothing. Between the steps of a read it only reads the memory size unless the memory
|
||||
//! grew.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
|
||||
/// A WebAssembly memory page.
|
||||
const PAGE: usize = 64 * 1024;
|
||||
|
||||
/// The most room reserved at once: past a heap of twice this, the heap grows by this much a step
|
||||
/// rather than by half, so a page close to the browser's limit doesn't ask for more than it needs.
|
||||
const MAX_STEP: usize = 256 << 20;
|
||||
|
||||
/// How many bytes of room to reserve when the memory is `now` pages and was `seen` pages at the
|
||||
/// last look (0: never looked, so only the size is noted).
|
||||
fn room(seen: usize, now: usize) -> Option<usize> {
|
||||
(seen != 0 && now > seen).then(|| (now.saturating_mul(PAGE) / 2).min(MAX_STEP))
|
||||
}
|
||||
|
||||
/// How many snapshot reads are under way (a full snapshot is applied inside a welcome's read).
|
||||
static READING: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// The memory size at the last look, in pages.
|
||||
static SEEN: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Set when a reservation fails near the browser's memory limit so the rest of this read does not
|
||||
/// retry failing large reservations on every subsequent growth.
|
||||
static EXHAUSTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// A snapshot read under way: [`keep_ahead`] acts until it is dropped, on error paths too.
|
||||
pub(crate) struct Reading(());
|
||||
|
||||
impl Drop for Reading {
|
||||
fn drop(&mut self) {
|
||||
READING.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Start a snapshot read: growth from here on gets room kept ahead.
|
||||
pub(crate) fn reading() -> Reading {
|
||||
if READING.fetch_add(1, Ordering::Relaxed) == 0 {
|
||||
EXHAUSTED.store(false, Ordering::Relaxed);
|
||||
SEEN.store(memory_pages().unwrap_or(0), Ordering::Relaxed);
|
||||
}
|
||||
Reading(())
|
||||
}
|
||||
|
||||
/// Reserve room ahead in the heap if a snapshot is being read and the memory grew since the last
|
||||
/// call (see the module docs).
|
||||
pub(crate) fn keep_ahead() {
|
||||
if READING.load(Ordering::Relaxed) == 0 || EXHAUSTED.load(Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
let Some(now) = memory_pages() else { return };
|
||||
if let Some(bytes) = room(SEEN.load(Ordering::Relaxed), now) {
|
||||
let mut block: Vec<u8> = Vec::new();
|
||||
// Near the browser's memory limit this fails and nothing changes: stop trying large
|
||||
// reservations for the rest of this read and let the heap grow as needed.
|
||||
if block.try_reserve_exact(bytes).is_ok() {
|
||||
// Opaque to the optimizer, which could otherwise drop an allocation nothing reads.
|
||||
drop(std::hint::black_box(block));
|
||||
} else {
|
||||
EXHAUSTED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
SEEN.store(memory_pages().unwrap_or(now), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The size of the page's memory in pages (`None` off the web: the system allocator there maps
|
||||
/// large blocks on its own).
|
||||
fn memory_pages() -> Option<usize> {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
Some(core::arch::wasm32::memory_size(0))
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{PAGE, room};
|
||||
|
||||
/// A heap that grows by whole pages when an allocation doesn't fit, as the web allocator's.
|
||||
struct Heap {
|
||||
pages: usize,
|
||||
free: usize,
|
||||
grows: usize,
|
||||
seen: usize,
|
||||
}
|
||||
|
||||
impl Heap {
|
||||
fn alloc(&mut self, n: usize) {
|
||||
if self.free < n {
|
||||
let pages = (n - self.free).div_ceil(PAGE);
|
||||
self.pages += pages;
|
||||
self.free += pages * PAGE;
|
||||
self.grows += 1;
|
||||
}
|
||||
self.free -= n;
|
||||
}
|
||||
|
||||
fn keep_ahead(&mut self) {
|
||||
if let Some(bytes) = room(self.seen, self.pages) {
|
||||
self.alloc(bytes);
|
||||
self.free += bytes;
|
||||
}
|
||||
self.seen = self.pages;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reading a file the size of #2041's (46 MB to 1.66 GB in small allocations) grows the heap
|
||||
/// in a few dozen steps with room kept ahead between allocations, not in one step per page.
|
||||
#[test]
|
||||
fn room_kept_ahead_turns_page_by_page_growth_into_a_few_steps() {
|
||||
let run = |ahead: bool| {
|
||||
let mut h = Heap { pages: (46 << 20) / PAGE, free: 0, grows: 0, seen: 0 };
|
||||
while h.pages * PAGE < 1660 << 20 {
|
||||
h.alloc(400);
|
||||
if ahead {
|
||||
h.keep_ahead();
|
||||
}
|
||||
}
|
||||
h.grows
|
||||
};
|
||||
let (plain, ahead) = (run(false), run(true));
|
||||
assert!(plain > 20_000, "page by page: {plain} grows");
|
||||
assert!(ahead * 200 < plain, "{ahead} grows with room kept ahead, {plain} without");
|
||||
}
|
||||
|
||||
/// The first look only notes the size, and an unchanged or smaller memory reserves nothing.
|
||||
#[test]
|
||||
fn room_is_reserved_only_after_the_memory_grew() {
|
||||
assert_eq!(room(0, 1000), None);
|
||||
assert_eq!(room(1000, 1000), None);
|
||||
assert!(room(1000, 1001).is_some());
|
||||
assert!(room(1000, 1001) <= room(5000, 5001), "more room for a larger heap");
|
||||
}
|
||||
}
|
||||
@@ -169,7 +169,7 @@ fn a_snapshot_holding_an_image_the_checks_refuse_still_opens_without_it() {
|
||||
let mut snapshot = crate::Replica::new(crate::sim_tests::base()).snapshot().unwrap();
|
||||
let (key, bytes) = forged();
|
||||
snapshot.push(put(&key, 2, 1, bytes));
|
||||
let r = crate::Replica::from_snapshot(&snapshot).expect("the snapshot opens");
|
||||
let r = crate::Replica::from_snapshot(snapshot).expect("the snapshot opens");
|
||||
assert!(!r.document().images.contains_key(&key));
|
||||
}
|
||||
|
||||
@@ -254,5 +254,5 @@ fn a_snapshot_with_a_broken_layer_change_still_fails_to_open() {
|
||||
// A property of a layer that isn't there: an error when applied (unlike deleting it).
|
||||
let missing = figcraft_doc::NodeId(u64::MAX);
|
||||
snapshot.push(Change::Set { id: missing, prop: crate::change::Prop::Name, value: Json(json!("x")) });
|
||||
assert!(crate::Replica::from_snapshot(&snapshot).is_err());
|
||||
assert!(crate::Replica::from_snapshot(snapshot).is_err());
|
||||
}
|
||||
@@ -303,7 +303,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
|
||||
let (key, bytes) = crate::image_tests::forged();
|
||||
state.snapshot.push(crate::image_tests::put(&key, 2, 1, bytes));
|
||||
let mut r = Server::restore(state, "", Limits::default()).unwrap();
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on restore");
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on restore");
|
||||
|
||||
// Left out on replay.
|
||||
let mut s = Server::new(base(), "", Limits::default());
|
||||
@@ -312,7 +312,7 @@ fn a_resume_after_history_was_left_out_catches_up_with_the_snapshot() {
|
||||
let mut r = Server::restore(state.clone(), "", Limits::default()).unwrap();
|
||||
let batch = vec![crate::image_tests::put(&key, 2, 1, bytes)];
|
||||
r.replay(Journal::Accepted(message::Accepted { seq: state.seq + 1, author: a.id(), batch_id: 90, changes: batch })).unwrap();
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_)), "left out on replay");
|
||||
assert!(matches!(catch_up_of(&mut r, &mut a), message::CatchUp::Snapshot(_) | message::CatchUp::DeltaSnapshot(_)), "left out on replay");
|
||||
}
|
||||
|
||||
/// A restart that left nothing out keeps resuming clients on the cheaper delta.
|
||||
|
||||
@@ -24,9 +24,11 @@
|
||||
pub mod change;
|
||||
pub mod client;
|
||||
pub mod code;
|
||||
pub mod delta_snapshot;
|
||||
mod diff;
|
||||
mod docprops;
|
||||
pub mod frac;
|
||||
mod heap;
|
||||
mod history;
|
||||
pub mod merge;
|
||||
pub mod message;
|
||||
@@ -143,8 +145,14 @@ mod comment_access_tests;
|
||||
#[cfg(test)]
|
||||
mod deleted_cap_tests;
|
||||
#[cfg(test)]
|
||||
mod delta_dst_tests;
|
||||
#[cfg(test)]
|
||||
mod delta_snapshot_tests;
|
||||
#[cfg(test)]
|
||||
mod diff_tests;
|
||||
#[cfg(test)]
|
||||
mod dst_fault_tests;
|
||||
#[cfg(test)]
|
||||
mod entry_ids_tests;
|
||||
#[cfg(test)]
|
||||
mod frac_tests;
|
||||
|
||||
@@ -44,9 +44,14 @@ pub const BRANCHES: &str = "branches";
|
||||
/// (older ones couldn't decode the variant at all).
|
||||
pub const DESIGN_REVIEW: &str = "design-review";
|
||||
|
||||
/// The word a client puts in its [`Hello::client_version`] when it reads
|
||||
/// [`CatchUp::DeltaSnapshot`]: a server sends a direct value-checked mirror-delta + vector-dedup
|
||||
/// compressed snapshot instead of `Vec<Change>` (#1819, #2041).
|
||||
pub const DELTA_SNAPSHOT: &str = "delta-snapshot";
|
||||
|
||||
/// The `client_version` this build announces: its version, then what it reads beyond the protocol.
|
||||
pub fn client_version() -> String {
|
||||
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES}", env!("CARGO_PKG_VERSION"))
|
||||
format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW} {BRANCHES} {DELTA_SNAPSHOT}", env!("CARGO_PKG_VERSION"))
|
||||
}
|
||||
|
||||
/// Whether `client_version` announces `word`.
|
||||
@@ -84,6 +89,11 @@ pub fn reads_branches(client_version: &str) -> bool {
|
||||
announces(client_version, BRANCHES)
|
||||
}
|
||||
|
||||
/// A [`Hello::client_version`] that announces [`DELTA_SNAPSHOT`].
|
||||
pub fn reads_delta_snapshot(client_version: &str) -> bool {
|
||||
announces(client_version, DELTA_SNAPSHOT)
|
||||
}
|
||||
|
||||
/// Join a file's session.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Hello {
|
||||
@@ -353,6 +363,10 @@ pub enum CatchUp {
|
||||
/// [`PACKED`]: a document's changes shrink several times over. The client reads it with
|
||||
/// [`unpack`] before anything else sees the welcome.
|
||||
Packed(Vec<u8>),
|
||||
/// A direct compressed mirror-delta & vector-deduplicated snapshot
|
||||
/// ([`crate::delta_snapshot`]), for a client whose hello announced [`DELTA_SNAPSHOT`].
|
||||
/// Appended last so earlier postcard discriminants remain unchanged.
|
||||
DeltaSnapshot(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Opens a connection that manages a server's files (instead of [`Hello`]): the server's admin
|
||||
@@ -1175,19 +1189,26 @@ pub fn pack(msg: &mut ServerMsg) -> Result<(), Error> {
|
||||
/// past `max_bytes` (untrusted input: the limit an unpacked welcome would have had to fit).
|
||||
/// Anything else is left as it is.
|
||||
pub fn unpack(msg: &mut ServerMsg, max_bytes: usize) -> Result<(), Error> {
|
||||
if let ServerMsg::Welcome { catch_up, .. } = msg
|
||||
&& let CatchUp::Packed(packed) = catch_up
|
||||
{
|
||||
let mut raw = Vec::new();
|
||||
let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
|
||||
flate2::read::DeflateDecoder::new(packed.as_slice())
|
||||
.take(limit)
|
||||
.read_to_end(&mut raw)
|
||||
.map_err(|e| Error::Decode(format!("packed document: {e}")))?;
|
||||
if raw.len() > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
if let ServerMsg::Welcome { catch_up, .. } = msg {
|
||||
match catch_up {
|
||||
CatchUp::Packed(packed) => {
|
||||
let _reading = crate::heap::reading();
|
||||
let mut raw = Vec::new();
|
||||
let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX).saturating_add(1);
|
||||
flate2::read::DeflateDecoder::new(packed.as_slice())
|
||||
.take(limit)
|
||||
.read_to_end(&mut raw)
|
||||
.map_err(|e| Error::Decode(format!("packed document: {e}")))?;
|
||||
if raw.len() > max_bytes {
|
||||
return Err(Error::TooLarge(max_bytes));
|
||||
}
|
||||
*catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
|
||||
}
|
||||
CatchUp::DeltaSnapshot(bytes) => {
|
||||
crate::delta_snapshot::check_header_limit(bytes, max_bytes)?;
|
||||
}
|
||||
CatchUp::Snapshot(_) | CatchUp::Delta(_) => {}
|
||||
}
|
||||
*catch_up = CatchUp::Snapshot(from_postcard(&raw)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -23,7 +23,9 @@ fn welcome() -> ServerMsg {
|
||||
}
|
||||
doc.repair();
|
||||
let mut s = Server::new(doc, "tok", Limits::default());
|
||||
let ClientMsg::Hello(h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
|
||||
let ClientMsg::Hello(mut h) = Client::hello("f", "tok", "Ada", "#FF8800") else { panic!("not a hello") };
|
||||
// Test the legacy `packed` welcome path (a client from before `delta-snapshot`).
|
||||
h.client_version = "0.18.1 signals hosting comments packed design-review branches".into();
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
out.into_iter().find_map(|o| if let Outgoing::To(_, m @ ServerMsg::Welcome { .. }) = o { Some(m) } else { None }).unwrap()
|
||||
}
|
||||
@@ -55,7 +57,7 @@ fn a_packed_welcome_is_much_smaller_and_reads_back_the_same() {
|
||||
assert_eq!(back, plain);
|
||||
// The client opens the same document from it.
|
||||
let ServerMsg::Welcome { catch_up: CatchUp::Snapshot(changes), .. } = &plain else { panic!("not a snapshot") };
|
||||
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes).unwrap().document());
|
||||
assert_eq!(Client::join(back).unwrap().document(), Replica::from_snapshot(changes.clone()).unwrap().document());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -117,7 +117,7 @@ fn a_long_absence_catches_up_with_a_snapshot() {
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
// A short absence gets the missed batches only.
|
||||
@@ -154,7 +154,7 @@ fn the_default_log_is_bounded_in_bytes_and_a_client_behind_it_catches_up_with_a_
|
||||
assert!(s.log_bytes() > 0, "recent batches are still kept");
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
// Within the log, a short absence still gets the missed batch only.
|
||||
@@ -195,7 +195,7 @@ fn after_a_snapshot_undo_leaves_what_others_changed_meanwhile() {
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })));
|
||||
deliver(&mut a, &out);
|
||||
// Undo: the page name goes back, the frame keeps b's later name.
|
||||
let msgs = a.undo(&NoRecompute).unwrap();
|
||||
@@ -326,7 +326,7 @@ fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() {
|
||||
let (id, out) = restored.join(h).unwrap();
|
||||
assert_eq!(id, b.id(), "a reconnecting client keeps its id");
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_) | CatchUp::DeltaSnapshot(_), .. })),
|
||||
"a clamped session hands out the snapshot, not a batch past the limits: {out:?}"
|
||||
);
|
||||
deliver(&mut b, &out);
|
||||
@@ -394,3 +394,33 @@ fn resume_needs_the_issued_secret() {
|
||||
let resend = come_back(&mut s, &mut host);
|
||||
assert!(resend.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_legacy_client_without_delta_snapshot_catches_up_with_a_legacy_snapshot() {
|
||||
let mut s = Server::new(base(), "tok", Limits { max_log_batches: 2, ..Limits::default() });
|
||||
let legacy_hello = || Hello { client_version: "0.18.1 signals hosting comments packed design-review branches".into(), ..hello() };
|
||||
let (_, out) = s.join(legacy_hello()).unwrap();
|
||||
assert!(matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })));
|
||||
let Outgoing::To(_, w) = out.into_iter().next().unwrap() else { panic!() };
|
||||
let mut a = Client::join(w).unwrap();
|
||||
let mut b = join(&mut s);
|
||||
let page = s.document().first_page().unwrap();
|
||||
|
||||
// Disconnect legacy client `a` and overflow the 2-batch server log so `a` must catch up via
|
||||
// legacy `CatchUp::Snapshot` (never `DeltaSnapshot`).
|
||||
a.disconnect();
|
||||
s.leave(a.id());
|
||||
for i in 0..4 {
|
||||
let m = edit(&mut b, |d| d.node_mut(page).unwrap().name = format!("Legacy {i}")).unwrap();
|
||||
let out = s.receive(b.id(), m);
|
||||
deliver(&mut b, &out);
|
||||
}
|
||||
let ClientMsg::Hello(h) = a.reconnect(legacy_hello()) else { panic!() };
|
||||
let (_, out) = s.join(h).unwrap();
|
||||
assert!(
|
||||
matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })),
|
||||
"legacy client without delta-snapshot must receive CatchUp::Snapshot on rejoin"
|
||||
);
|
||||
deliver(&mut a, &out);
|
||||
assert_eq!(a.view(), s.replica());
|
||||
}
|
||||
@@ -70,8 +70,10 @@ impl Replica {
|
||||
Replica { doc, positions }
|
||||
}
|
||||
|
||||
/// Rebuild a replica from a [`snapshot`](Self::snapshot).
|
||||
pub fn from_snapshot(changes: &[Change]) -> Result<Replica, Error> {
|
||||
/// Rebuild a replica from a [`snapshot`](Self::snapshot). It takes the changes, so a large
|
||||
/// file's snapshot isn't copied on the way in (#2041): the few that need it (review settings
|
||||
/// past the limits) are rewritten in place.
|
||||
pub fn from_snapshot(changes: Vec<Change>) -> Result<Replica, Error> {
|
||||
Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r)
|
||||
}
|
||||
|
||||
@@ -81,9 +83,9 @@ impl Replica {
|
||||
/// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened,
|
||||
/// because a session whose settings had to be clamped can no longer replay its saved batches
|
||||
/// for clients that resume (they hold the value past the limits).
|
||||
pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> {
|
||||
pub(crate) fn from_snapshot_leaving_out(mut changes: Vec<Change>) -> Result<(Replica, usize, bool), Error> {
|
||||
let _reading = crate::heap::reading();
|
||||
let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() };
|
||||
let mut changes = changes.to_vec();
|
||||
let clamped = docprops::clamp_snapshot_design_review(&mut changes);
|
||||
let left_out = r.apply_kept(&mut changes, Change::is_image)?;
|
||||
if r.doc.pages.is_empty() {
|
||||
@@ -199,6 +201,9 @@ impl Replica {
|
||||
let (mut relist, mut relist_all) = (BTreeSet::new(), false);
|
||||
let mut index = docprops::Index::default();
|
||||
for c in changes {
|
||||
// While a snapshot is applied, on the web the heap grows in large steps instead of
|
||||
// page by page ([`crate::heap`]); a live batch doesn't reserve anything.
|
||||
crate::heap::keep_ahead();
|
||||
match self.apply_one(c, &mut out, &mut index) {
|
||||
Ok(Relist::No) => {}
|
||||
Ok(Relist::Page(p)) => {
|
||||
|
||||
@@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize};
|
||||
use crate::change::{Change, Entry, Family, Prop, Target};
|
||||
use crate::message::{
|
||||
Accepted, Access, BranchEvent, BranchReq, BranchStatus, CatchUp, ClientMsg, Hello, MAX_SHARED_BRANCHES, PROTOCOL, Peer, Presence, Processed,
|
||||
Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_design_review, reads_signals,
|
||||
Resume, ServerMsg, SharedBranch, Signal, reads_branches, reads_comments, reads_delta_snapshot, reads_design_review, reads_signals,
|
||||
};
|
||||
use crate::replica::{Mode, Replica, create_change};
|
||||
use crate::{Error, Limits, diff, docprops, same_secret};
|
||||
@@ -126,6 +126,9 @@ pub struct Server {
|
||||
/// resuming client other bytes under a key it holds): every resuming client catches up with
|
||||
/// the snapshot, not the log.
|
||||
resync: bool,
|
||||
/// Cached compressed [`CatchUp::DeltaSnapshot`] for `self.seq`, so repeated joins of large
|
||||
/// files pay ~0 ms server CPU while no edit has arrived (#1819).
|
||||
delta_cache: Option<(u64, Vec<u8>)>,
|
||||
}
|
||||
|
||||
/// The most client ids a session remembers for reconnecting (the oldest disconnected ones go
|
||||
@@ -188,6 +191,7 @@ impl Server {
|
||||
design_review: BTreeSet::new(),
|
||||
spotlight: None,
|
||||
resync: false,
|
||||
delta_cache: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +214,7 @@ impl Server {
|
||||
/// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped
|
||||
/// (clients then catch up with a snapshot).
|
||||
pub fn restore(state: SessionState, token: impl Into<String>, limits: Limits) -> Result<Server, Error> {
|
||||
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?;
|
||||
let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(state.snapshot)?;
|
||||
let mut server = Server::new(replica.document().clone(), token, limits);
|
||||
server.state = replica;
|
||||
server.session = state.session;
|
||||
@@ -417,10 +421,21 @@ impl Server {
|
||||
// The log holds every batch after `floor`.
|
||||
let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1));
|
||||
let reads_design_review = reads_design_review(&hello.client_version);
|
||||
let reads_delta = reads_delta_snapshot(&hello.client_version);
|
||||
let catch_up = match resume {
|
||||
Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => {
|
||||
CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect())
|
||||
}
|
||||
// Only send the cached delta snapshot to peers that also read `design-review`, since
|
||||
// the compressed payload carries the document's review config without per-peer filtering,
|
||||
// and only when the document fits within the client decoder's default node cap.
|
||||
// If delta encoding fails (e.g. materialized budget exceeded), fall back to `Snapshot`.
|
||||
_ if reads_delta && reads_design_review && self.state.document().node_count() <= Limits::default().max_nodes => {
|
||||
match self.cached_delta_snapshot() {
|
||||
Ok(bytes) => CatchUp::DeltaSnapshot(bytes),
|
||||
Err(_) => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
|
||||
}
|
||||
}
|
||||
_ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?),
|
||||
};
|
||||
// A peer that doesn't read the review settings can't decode them: its catch-up carries
|
||||
@@ -686,9 +701,27 @@ impl Server {
|
||||
}
|
||||
self.state = next;
|
||||
self.seq += 1;
|
||||
self.delta_cache = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the cached compressed delta snapshot for `self.seq`, building it once on cache miss.
|
||||
/// Snapshots larger than 16 MiB compressed (e.g. files with large embedded images) are still
|
||||
/// sent, but are not pinned in `self.delta_cache` so room memory stays bounded.
|
||||
fn cached_delta_snapshot(&mut self) -> Result<Vec<u8>, Error> {
|
||||
const MAX_DELTA_CACHE_BYTES: usize = 16 << 20;
|
||||
if let Some((seq, bytes)) = &self.delta_cache
|
||||
&& *seq == self.seq
|
||||
{
|
||||
return Ok(bytes.clone());
|
||||
}
|
||||
let bytes = crate::delta_snapshot::encode_delta_snapshot(&self.state)?;
|
||||
if bytes.len() <= MAX_DELTA_CACHE_BYTES {
|
||||
self.delta_cache = Some((self.seq, bytes.clone()));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// The document-level entries (styles, variables, collections, comments) a batch adds or
|
||||
/// removes, each with whether it is there afterwards. A new one is refused when its id lies in
|
||||
/// the space of another client this session gave an id to, or in a space at or above
|
||||
|
||||
@@ -417,15 +417,15 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() {
|
||||
let for_new = for_client(&out, capable.id());
|
||||
assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}");
|
||||
|
||||
// A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings.
|
||||
// A capable newcomer's catch-up (a fresh join, so a delta snapshot) carries the settings.
|
||||
let (_, out) = s.join(hello("tok")).unwrap();
|
||||
let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) =
|
||||
let Some(Outgoing::To(_, welcome @ ServerMsg::Welcome { .. })) =
|
||||
out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. })))
|
||||
else {
|
||||
panic!("no welcome");
|
||||
};
|
||||
let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") };
|
||||
assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}");
|
||||
let joined = Client::join(welcome).unwrap();
|
||||
assert!(!joined.document().design_review.is_default(), "capable newcomer carries design review settings");
|
||||
|
||||
// An old newcomer's catch-up carries none, and still has the rename.
|
||||
let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap();
|
||||
|
||||
@@ -96,6 +96,11 @@ pub struct Sim {
|
||||
pub undos: usize,
|
||||
/// Reconnects that caught up with a snapshot (the missed batches were no longer logged).
|
||||
pub snapshots: usize,
|
||||
/// Reconnects by kind of catch-up: the missed batches from the log (at least one), a compressed
|
||||
/// snapshot, a plain snapshot (clients that don't read the compressed one).
|
||||
pub log_catch_ups: usize,
|
||||
pub delta_snapshots: usize,
|
||||
pub plain_snapshots: usize,
|
||||
/// Undo or redo batches that reverted a write by someone else the client had already seen.
|
||||
pub violations: Vec<String>,
|
||||
}
|
||||
@@ -129,6 +134,9 @@ impl Sim {
|
||||
repairs: 0,
|
||||
undos: 0,
|
||||
snapshots: 0,
|
||||
log_catch_ups: 0,
|
||||
delta_snapshots: 0,
|
||||
plain_snapshots: 0,
|
||||
violations: Vec::new(),
|
||||
};
|
||||
for i in 0..n {
|
||||
@@ -184,6 +192,26 @@ impl Sim {
|
||||
self.online.get(i).copied().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Client `i` says it runs `version` from its next reconnect on (e.g. an older app that
|
||||
/// doesn't read compressed snapshots).
|
||||
pub fn set_version(&mut self, i: usize, version: &str) {
|
||||
if let Some(h) = self.hellos.get_mut(i) {
|
||||
h.client_version = version.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
/// Hold back what is in flight on client `i`'s link to the server (`up`) or from it by
|
||||
/// `ticks` more, and what is sent on it next too: a one-way stall that keeps the order.
|
||||
pub fn stall(&mut self, i: usize, up: bool, ticks: u64) {
|
||||
let link = if up { self.up.get_mut(i) } else { self.down.get_mut(i) };
|
||||
if let Some(link) = link {
|
||||
for (due, _) in &mut link.queue {
|
||||
*due += ticks;
|
||||
}
|
||||
link.last_due = link.last_due.max(self.now) + ticks;
|
||||
}
|
||||
}
|
||||
|
||||
fn client(&mut self, i: usize) -> Result<&mut Client, Error> {
|
||||
self.clients.get_mut(i).ok_or_else(|| Error::Invalid(format!("no client {i}")))
|
||||
}
|
||||
@@ -291,7 +319,19 @@ impl Sim {
|
||||
let ClientMsg::Hello(hello) = hello else { return Err(Error::Protocol("hello".into())) };
|
||||
let seen = self.clients.get(i).map_or(0, Client::seq);
|
||||
let (id, out) = self.server.join(hello).map_err(|m| Error::Protocol(format!("{m:?}")))?;
|
||||
if out.iter().any(|o| matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_), .. }) if *to == id)) {
|
||||
let catch_up = out.iter().find_map(|o| match o {
|
||||
Outgoing::To(to, ServerMsg::Welcome { catch_up, .. }) if *to == id => Some(catch_up),
|
||||
_ => None,
|
||||
});
|
||||
match catch_up {
|
||||
Some(crate::CatchUp::Delta(d)) if !d.is_empty() => self.log_catch_ups += 1,
|
||||
Some(crate::CatchUp::DeltaSnapshot(_)) => self.delta_snapshots += 1,
|
||||
Some(crate::CatchUp::Snapshot(_) | crate::CatchUp::Packed(_)) => self.plain_snapshots += 1,
|
||||
_ => {}
|
||||
}
|
||||
if out.iter().any(|o| {
|
||||
matches!(o, Outgoing::To(to, ServerMsg::Welcome { catch_up: crate::CatchUp::Snapshot(_) | crate::CatchUp::DeltaSnapshot(_), .. }) if *to == id)
|
||||
}) {
|
||||
self.snapshots += 1;
|
||||
if let Some(g) = self.gaps.get_mut(i) {
|
||||
g.push((seen, self.server.seq()));
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Code blocks (#2237): the languages a block is highlighted as, and the numbers of its look.
|
||||
//! Pure data: the engine makes the block ([`crate::BoardItem::CodeBlock`]).
|
||||
//! Code blocks (#2237): the languages a block is highlighted as, the numbers of its look, and
|
||||
//! which stretches of its code are keywords, strings, numbers and comments. Pure data: the engine
|
||||
//! makes the block ([`crate::BoardItem::CodeBlock`]) and colours its text.
|
||||
|
||||
use figcraft_color::Color;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -116,3 +117,207 @@ pub const CODE_TEXT: Color = Color::from_rgb8_const(0xE3, 0xE1, 0xDD);
|
||||
pub fn code_height(lines: usize) -> f64 {
|
||||
CODE_PAD[0] + CODE_PAD[2] + CODE_LINE * lines.clamp(CODE_MIN_LINES, 1_000_000) as f64
|
||||
}
|
||||
|
||||
/// What a stretch of code is, for its colour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum CodeToken {
|
||||
Keyword,
|
||||
String,
|
||||
Number,
|
||||
Comment,
|
||||
}
|
||||
|
||||
impl CodeToken {
|
||||
/// Its colour on the panel (FigCraft's own, each at least 4.5:1 on [`CODE_PANEL`]).
|
||||
pub fn color(self) -> Color {
|
||||
match self {
|
||||
CodeToken::Keyword => Color::from_rgb8_const(0x86, 0xB0, 0xFF),
|
||||
CodeToken::String => Color::from_rgb8_const(0xA3, 0xD9, 0x8F),
|
||||
CodeToken::Number => Color::from_rgb8_const(0xF5, 0xC5, 0x6E),
|
||||
CodeToken::Comment => Color::from_rgb8_const(0x9C, 0x9C, 0x9C),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a language writes keywords, comments and strings.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Syntax {
|
||||
/// Its keywords, apart by spaces.
|
||||
keywords: &'static str,
|
||||
/// Keywords in any case (SQL).
|
||||
any_case: bool,
|
||||
/// What starts a comment to the end of the line.
|
||||
line: &'static [&'static str],
|
||||
/// Stretches from an opening to a closing mark, over lines.
|
||||
blocks: &'static [(&'static str, &'static str, CodeToken)],
|
||||
/// What opens and closes a string on one line.
|
||||
quotes: &'static [char],
|
||||
/// Markup: the name after `<` or `</` is a keyword, and quotes are strings only inside a tag.
|
||||
tags: bool,
|
||||
}
|
||||
|
||||
const PLAIN: Syntax = Syntax { keywords: "", any_case: false, line: &[], blocks: &[], quotes: &[], tags: false };
|
||||
const C_BLOCK: (&str, &str, CodeToken) = ("/*", "*/", CodeToken::Comment);
|
||||
const TRIPLE: (&str, &str, CodeToken) = ("\"\"\"", "\"\"\"", CodeToken::String);
|
||||
const BACKTICK: (&str, &str, CodeToken) = ("`", "`", CodeToken::String);
|
||||
const BOTH_QUOTES: &[char] = &['"', '\''];
|
||||
const JS: &str = "async await break case catch class const continue debugger default delete do else export extends false finally for from function if import in instanceof let new null of return static super switch this throw true try typeof undefined var void while yield";
|
||||
const TS: &str = "abstract any as async await boolean break case catch class const continue debugger declare default delete do else enum export extends false finally for from function if implements import in instanceof interface keyof let namespace never new null number of private protected public readonly return static string super switch this throw true try type typeof undefined unknown var void while yield";
|
||||
|
||||
/// A language with `//` and `/* */` comments, and `blocks` beside them.
|
||||
const fn c_like(keywords: &'static str, quotes: &'static [char], blocks: &'static [(&'static str, &'static str, CodeToken)]) -> Syntax {
|
||||
Syntax { keywords, line: &["//"], blocks, quotes, ..PLAIN }
|
||||
}
|
||||
|
||||
impl CodeLanguage {
|
||||
fn syntax(self) -> Syntax {
|
||||
match self {
|
||||
CodeLanguage::PlainText => PLAIN,
|
||||
CodeLanguage::Bash => Syntax {
|
||||
keywords: "alias break case continue declare do done elif else esac exit export false fi for function if in local readonly return select shift source then true unset until while",
|
||||
line: &["#"],
|
||||
quotes: BOTH_QUOTES,
|
||||
..PLAIN
|
||||
},
|
||||
CodeLanguage::Cpp => c_like(
|
||||
"auto bool break case catch char class const constexpr continue default define delete do double else enum explicit extern false float for friend goto if include inline int long mutable namespace new noexcept nullptr operator private protected public return short signed sizeof static struct switch template this throw true try typedef typename union unsigned using virtual void volatile while",
|
||||
BOTH_QUOTES,
|
||||
&[C_BLOCK],
|
||||
),
|
||||
CodeLanguage::Css => Syntax { keywords: "import important keyframes media supports", blocks: &[C_BLOCK], quotes: BOTH_QUOTES, ..PLAIN },
|
||||
CodeLanguage::Go => c_like(
|
||||
"break case chan const continue default defer else fallthrough false for func go goto if import interface iota map nil package range return select struct switch true type var",
|
||||
BOTH_QUOTES,
|
||||
&[C_BLOCK, BACKTICK],
|
||||
),
|
||||
CodeLanguage::Graphql => Syntax {
|
||||
keywords: "directive enum extend false fragment implements input interface mutation null on query scalar schema subscription true type union",
|
||||
line: &["#"],
|
||||
blocks: &[TRIPLE],
|
||||
quotes: &['"'],
|
||||
..PLAIN
|
||||
},
|
||||
CodeLanguage::Html => Syntax { blocks: &[("<!--", "-->", CodeToken::Comment)], quotes: BOTH_QUOTES, tags: true, ..PLAIN },
|
||||
CodeLanguage::Javascript => c_like(JS, BOTH_QUOTES, &[C_BLOCK, BACKTICK]),
|
||||
CodeLanguage::Typescript => c_like(TS, BOTH_QUOTES, &[C_BLOCK, BACKTICK]),
|
||||
CodeLanguage::Json => Syntax { keywords: "false null true", quotes: &['"'], ..PLAIN },
|
||||
CodeLanguage::Kotlin => c_like(
|
||||
"as break by class companion continue data do else enum false for fun if import in init interface internal is null object open override package private protected public return sealed super suspend this throw true try typealias val var when while",
|
||||
BOTH_QUOTES,
|
||||
&[C_BLOCK, TRIPLE],
|
||||
),
|
||||
CodeLanguage::Python => Syntax {
|
||||
keywords: "False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return self try while with yield",
|
||||
line: &["#"],
|
||||
blocks: &[TRIPLE, ("'''", "'''", CodeToken::String)],
|
||||
quotes: BOTH_QUOTES,
|
||||
..PLAIN
|
||||
},
|
||||
CodeLanguage::Ruby => Syntax {
|
||||
keywords: "alias and begin break case class def defined do else elsif end ensure false for if in module next nil not or redo require rescue retry return self super then true undef unless until when while yield",
|
||||
line: &["#"],
|
||||
quotes: BOTH_QUOTES,
|
||||
..PLAIN
|
||||
},
|
||||
// Only double quotes: a single one also starts a lifetime.
|
||||
CodeLanguage::Rust => c_like(
|
||||
"Self as async await break const continue crate dyn else enum extern false fn for if impl in let loop match mod move mut pub ref return self static struct super trait true type unsafe use where while",
|
||||
&['"'],
|
||||
&[C_BLOCK],
|
||||
),
|
||||
CodeLanguage::Sql => Syntax {
|
||||
keywords: "all alter and as asc between by case count create default delete desc distinct drop else end exists foreign from full group having in index inner insert into is join key left like limit not null offset on or order outer primary references right select set table then union update values when where",
|
||||
any_case: true,
|
||||
line: &["--"],
|
||||
blocks: &[C_BLOCK],
|
||||
quotes: &['\''],
|
||||
..PLAIN
|
||||
},
|
||||
CodeLanguage::Swift => c_like(
|
||||
"Self as associatedtype break case catch class continue default defer do else enum extension fallthrough false for func guard if import in init inout internal is let nil operator private protocol public repeat rethrows return self static struct subscript super switch throw throws true try typealias var where while",
|
||||
&['"'],
|
||||
&[C_BLOCK, TRIPLE],
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a Rust character literal opening at `i` ends (`'a'`, `'\n'`, `'\u{1F600}'`), or `None`
|
||||
/// for a lifetime (`'a`), whose quote opens nothing.
|
||||
fn rust_char(chars: &[char], i: usize) -> Option<usize> {
|
||||
let close = if chars.get(i + 1) == Some(&'\\') { (i + 3..(i + 12).min(chars.len())).find(|&j| chars.get(j) == Some(&'\''))? } else { i + 2 };
|
||||
(chars.get(close) == Some(&'\'') && !chars.get(i + 1..close)?.contains(&'\n')).then_some(close + 1)
|
||||
}
|
||||
|
||||
/// The stretches of `text` that `language` colours, as char ranges (end exclusive), in order and
|
||||
/// apart: keywords, strings (a quoted one ends with its line), numbers and comments. Plain text
|
||||
/// colours nothing.
|
||||
pub fn code_tokens(language: CodeLanguage, text: &str) -> Vec<(usize, usize, CodeToken)> {
|
||||
if language == CodeLanguage::PlainText {
|
||||
return Vec::new();
|
||||
}
|
||||
let syn = language.syntax();
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let n = chars.len();
|
||||
let at = |i: usize, mark: &str| mark.chars().enumerate().all(|(k, c)| chars.get(i + k) == Some(&c));
|
||||
let word = |c: char| c.is_alphanumeric() || c == '_';
|
||||
let mut out = Vec::new();
|
||||
let (mut i, mut in_tag) = (0, false);
|
||||
while let Some(&c) = chars.get(i) {
|
||||
let prev = i.checked_sub(1).and_then(|p| chars.get(p)).copied();
|
||||
let next = if let Some(&(open, close, token)) = syn.blocks.iter().find(|(open, ..)| at(i, open)) {
|
||||
let from = i + open.chars().count();
|
||||
// A string's closing mark escaped by a backslash doesn't close it.
|
||||
let escaped = |j: usize| token == CodeToken::String && j.checked_sub(1).and_then(|p| chars.get(p)) == Some(&'\\');
|
||||
let end = (from..n).find(|&j| at(j, close) && !escaped(j)).map_or(n, |j| j + close.chars().count());
|
||||
out.push((i, end, token));
|
||||
end
|
||||
} else if syn.line.iter().any(|m| at(i, m))
|
||||
&& (c != '#' || language != CodeLanguage::Bash || prev.is_none_or(|p| p.is_whitespace() || ";|&()".contains(p)))
|
||||
{
|
||||
// In Bash a `#` starts a comment only at the start of a word, after a space or an
|
||||
// operator (`$#` and `a#b` are not).
|
||||
let end = (i..n).find(|&j| chars.get(j) == Some(&'\n')).unwrap_or(n);
|
||||
out.push((i, end, CodeToken::Comment));
|
||||
end
|
||||
} else if let Some(end) = (language == CodeLanguage::Rust && c == '\'').then(|| rust_char(&chars, i)).flatten() {
|
||||
out.push((i, end, CodeToken::String));
|
||||
end
|
||||
} else if syn.quotes.contains(&c) && (!syn.tags || in_tag) {
|
||||
let mut j = i + 1;
|
||||
while let Some(&d) = chars.get(j).filter(|d| **d != c && **d != '\n') {
|
||||
// An escape skips the next character, but never the end of the line.
|
||||
j += if d == '\\' && chars.get(j + 1).is_some_and(|e| *e != '\n') { 2 } else { 1 };
|
||||
}
|
||||
let end = if chars.get(j) == Some(&c) { j + 1 } else { j.min(n) };
|
||||
out.push((i, end, CodeToken::String));
|
||||
end
|
||||
} else if c.is_ascii_digit() && !prev.is_some_and(word) && !syn.tags {
|
||||
let mut j = i + 1;
|
||||
while chars.get(j).is_some_and(|d| word(*d) || (*d == '.' && chars.get(j + 1).is_some_and(char::is_ascii_digit))) {
|
||||
j += 1;
|
||||
}
|
||||
out.push((i, j, CodeToken::Number));
|
||||
j
|
||||
} else if word(c) && !c.is_ascii_digit() {
|
||||
let mut j = i + 1;
|
||||
while chars.get(j).is_some_and(|d| word(*d)) {
|
||||
j += 1;
|
||||
}
|
||||
let w: String = chars.get(i..j).unwrap_or(&[]).iter().collect();
|
||||
let tag_name = syn.tags && (prev == Some('<') || (prev == Some('/') && i.checked_sub(2).and_then(|p| chars.get(p)) == Some(&'<')));
|
||||
let keyword = syn.keywords.split_whitespace().any(|k| if syn.any_case { k.eq_ignore_ascii_case(&w) } else { k == w });
|
||||
if tag_name || keyword {
|
||||
out.push((i, j, CodeToken::Keyword));
|
||||
}
|
||||
j
|
||||
} else {
|
||||
if syn.tags && (c == '<' || c == '>') {
|
||||
in_tag = c == '<';
|
||||
}
|
||||
i + 1
|
||||
};
|
||||
i = next;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use serde_json::json;
|
||||
|
||||
use crate::BoardItem;
|
||||
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, code_height};
|
||||
use crate::board_code::{CODE_MIN_H, CODE_PAD, CODE_PANEL, CODE_TEXT, CodeLanguage, CodeToken, code_height, code_tokens};
|
||||
|
||||
#[test]
|
||||
fn sixteen_languages_by_name_with_typescript_the_default() {
|
||||
@@ -56,3 +56,92 @@ fn the_height_is_32_and_24_a_line_from_four_lines_up() {
|
||||
fn plain_code_reads_on_the_panel() {
|
||||
assert!(CODE_TEXT.contrast(CODE_PANEL) >= 4.5, "{}", CODE_TEXT.contrast(CODE_PANEL));
|
||||
}
|
||||
|
||||
/// The tokens of `text` in `language`, as the text they cover.
|
||||
fn tokens(language: CodeLanguage, text: &str) -> Vec<(String, CodeToken)> {
|
||||
code_tokens(language, text).into_iter().map(|(a, b, t)| (text.chars().skip(a).take(b - a).collect(), t)).collect()
|
||||
}
|
||||
|
||||
fn want(v: &[(&str, CodeToken)]) -> Vec<(String, CodeToken)> {
|
||||
v.iter().map(|(s, t)| ((*s).to_string(), *t)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords_strings_numbers_and_comments_per_language() {
|
||||
use CodeLanguage::*;
|
||||
use CodeToken::*;
|
||||
// A keyword inside a string or a comment is part of it.
|
||||
assert_eq!(
|
||||
tokens(
|
||||
Rust,
|
||||
"fn main() { let s = \"fn\"; // fn here
|
||||
x = 4.2; }"
|
||||
),
|
||||
want(&[("fn", Keyword), ("let", Keyword), ("\"fn\"", String), ("// fn here", Comment), ("4.2", Number)])
|
||||
);
|
||||
assert_eq!(tokens(Python, "def f(): # note"), want(&[("def", Keyword), ("# note", Comment)]));
|
||||
assert_eq!(tokens(Sql, "SELECT name FROM t -- all"), want(&[("SELECT", Keyword), ("FROM", Keyword), ("-- all", Comment)]));
|
||||
// A quoted string ends with its line; a block comment runs over lines.
|
||||
assert_eq!(
|
||||
tokens(
|
||||
Typescript,
|
||||
"const a = 'open
|
||||
let b /* x
|
||||
y */"
|
||||
),
|
||||
want(&[
|
||||
("const", Keyword),
|
||||
("'open", String),
|
||||
("let", Keyword),
|
||||
(
|
||||
"/* x
|
||||
y */",
|
||||
Comment
|
||||
)
|
||||
])
|
||||
);
|
||||
// Markup: tag names, quotes only inside a tag (an apostrophe in the text is none).
|
||||
assert_eq!(
|
||||
tokens(Html, "<a href=\"x\">don't</a> <!-- c -->"),
|
||||
want(&[("a", Keyword), ("\"x\"", String), ("a", Keyword), ("<!-- c -->", Comment)])
|
||||
);
|
||||
// `#` starts a comment only at the start of a word.
|
||||
assert_eq!(tokens(Bash, "echo $# a#b # c"), want(&[("# c", Comment)]));
|
||||
assert!(tokens(PlainText, "fn \"x\" 1 // y").is_empty());
|
||||
// Python's `#` needs no space before it; an escaped line end still ends a quoted string.
|
||||
assert_eq!(tokens(Python, "x=1# return \"x\""), want(&[("1", Number), ("# return \"x\"", Comment)]));
|
||||
assert_eq!(tokens(Json, "\"open\\\ntrue"), want(&[("\"open\\", String), ("true", Keyword)]));
|
||||
// An escaped backtick doesn't end a template string; a `#` after a Bash operator starts a comment.
|
||||
assert_eq!(
|
||||
tokens(Javascript, "const s = `a\\`b`; const n = 1;"),
|
||||
want(&[("const", Keyword), ("`a\\`b`", String), ("const", Keyword), ("1", Number)])
|
||||
);
|
||||
assert_eq!(tokens(Bash, "echo ok;# if true"), want(&[("# if true", Comment)]));
|
||||
// Rust: a character literal is a string, and a lifetime's quote opens nothing.
|
||||
assert_eq!(
|
||||
tokens(Rust, "let q = '\"'; let n = '\\n'; fn f<'a>(x: &'a str) {}"),
|
||||
want(&[("let", Keyword), ("'\"'", String), ("let", Keyword), ("'\\n'", String), ("fn", Keyword)])
|
||||
);
|
||||
// In every language the stretches are in order, apart and inside the text, even unclosed.
|
||||
let text = "if (x) { y = \"a\\\"b\" + 'c' + `d` /* e */ // f
|
||||
# g
|
||||
-- h
|
||||
<i j=\"k\"> 1.5 0x1F \"\"\" l";
|
||||
let n = text.chars().count();
|
||||
for l in CodeLanguage::ALL {
|
||||
let v = code_tokens(l, text);
|
||||
assert!(v.iter().all(|(a, b, _)| a < b && *b <= n), "{l:?}: {v:?}");
|
||||
assert!(v.windows(2).all(|w| w[0].1 <= w[1].0), "{l:?}: {v:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn highlight_colours_read_on_the_panel_and_differ() {
|
||||
let all = [CodeToken::Keyword, CodeToken::String, CodeToken::Number, CodeToken::Comment];
|
||||
for t in all {
|
||||
assert!(t.color().contrast(CODE_PANEL) >= 4.5, "{t:?}: {}", t.color().contrast(CODE_PANEL));
|
||||
assert_ne!(t.color(), CODE_TEXT, "{t:?}");
|
||||
}
|
||||
let distinct: std::collections::BTreeSet<String> = all.iter().map(|t| t.color().to_hex()).collect();
|
||||
assert_eq!(distinct.len(), all.len());
|
||||
}
|
||||
@@ -57,7 +57,7 @@ fn ordinary_hit_uses_region_paints_without_layer_fill() {
|
||||
Region { loops: vec![vec![0, 1, 2, 3]], winding: WindingRule::NonZero, fills: Some(Vec::new()), ..Default::default() },
|
||||
],
|
||||
};
|
||||
let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
d.get_mut(id).unwrap().fills.clear();
|
||||
assert!(d.node(id).unwrap().fills.is_empty());
|
||||
assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), Some(id));
|
||||
@@ -71,7 +71,7 @@ fn inherited_paint_frames_use_per_region_hit_testing() {
|
||||
let mut network = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true);
|
||||
network.regions[0].winding = WindingRule::EvenOdd;
|
||||
network.regions.push(network.regions[0].clone());
|
||||
let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
assert_eq!(d.hit_test(p, Point::new(5.0, 5.0), 0.0, None), None, "legacy even-odd loops cancel");
|
||||
let NodeKind::Vector { network } = &mut d.get_mut(id).unwrap().kind else { panic!("expected vector") };
|
||||
network.regions[0].paint_space = Some(crate::RegionPaintSpace { width: 10.0, height: 10.0, transform: figcraft_geom::Affine::IDENTITY });
|
||||
@@ -87,7 +87,7 @@ fn explicitly_unfilled_regions_keep_the_stroke_only_selection_band() {
|
||||
let mut network =
|
||||
VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)], true);
|
||||
network.regions[0].fills = Some(Vec::new());
|
||||
let id = d.create(p, NodeKind::Vector { network }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
|
||||
let id = d.create(p, NodeKind::Vector { network: network.into() }, "V", 0.0, 0.0, 100.0, 100.0).unwrap();
|
||||
let n = d.get_mut(id).unwrap();
|
||||
n.fills.clear();
|
||||
n.strokes = vec![figcraft_color::Paint::solid(figcraft_color::Color::BLACK)];
|
||||
|
||||
@@ -13,7 +13,7 @@ fn colourful() -> (Document, NodeId) {
|
||||
let mut d = Document::new("c");
|
||||
let p = d.first_page().unwrap();
|
||||
let r = d.create(p, NodeKind::Rectangle, "R", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let t = d.create(p, NodeKind::Text(TextData::default()), "T", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let t = d.create(p, NodeKind::Text(TextData::default().into()), "T", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
{
|
||||
let n = d.node_mut(r).unwrap();
|
||||
n.fills = vec![Paint::solid(RED)];
|
||||
|
||||
+77
-34
@@ -1,5 +1,6 @@
|
||||
//! Node geometry: local outline paths, and hit testing with Figma's click-target rules.
|
||||
|
||||
use crate::color::{ImagePaint, Paint, PaintKind};
|
||||
use crate::{Document, Node, NodeId, NodeKind};
|
||||
use figcraft_geom::{BezPath, Point, Rect, Shape};
|
||||
|
||||
@@ -14,7 +15,7 @@ pub fn shape_path(n: &Node) -> Option<BezPath> {
|
||||
| NodeKind::Component { .. }
|
||||
| NodeKind::ComponentSet { .. }
|
||||
| NodeKind::Instance { .. }
|
||||
| NodeKind::Section { .. } => figcraft_geom::rounded_rect(w, h, c.radii, c.smoothing),
|
||||
| NodeKind::Section { .. } => figcraft_geom::styled_rect(w, h, c.radii, c.smoothing, c.style),
|
||||
NodeKind::Slice => figcraft_geom::rounded_rect(w, h, [0.0; 4], 0.0),
|
||||
NodeKind::Ellipse { start, sweep, inner } => figcraft_geom::ellipse(w, h, *start, *sweep, *inner),
|
||||
NodeKind::Polygon { count } => figcraft_geom::smoothed_polygon(&figcraft_geom::polygon_points(w, h, *count), c.radii[0], c.smoothing),
|
||||
@@ -70,7 +71,7 @@ const STROKE_REACH: f64 = 2.5;
|
||||
|
||||
/// Whether `pt` hits `n` itself; in `outline` mode (nothing filled on the canvas) a shape only where
|
||||
/// its outline is.
|
||||
fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool) -> bool {
|
||||
fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool, image: ImageCoverage) -> bool {
|
||||
let inv = doc.world_transform(id).inverse();
|
||||
let lp = inv * pt;
|
||||
// Tolerance in local units (approximate under scale).
|
||||
@@ -84,6 +85,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
|
||||
}
|
||||
NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. } | NodeKind::Section { .. } => {
|
||||
n.local_rect().inflate(tol_l, tol_l).contains(lp)
|
||||
&& (n.corners.style.is_round() || shape_path(n).is_some_and(|path| path.contains(lp) || (tol_l > 0.0 && near_path(&path, lp, tol_l))))
|
||||
}
|
||||
NodeKind::Vector { network } if network.regions.iter().any(|r| r.fills.is_some() || r.paint_space.is_some()) => {
|
||||
let drawn = drawn_network(network, n.corners.smoothing);
|
||||
@@ -91,7 +93,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
|
||||
if !outline {
|
||||
for (i, region) in net.regions.iter().enumerate().rev() {
|
||||
let paints = region.fills.as_deref().unwrap_or(&n.fills);
|
||||
if paints.iter().any(|p| p.visible) && net.region_contains(i, lp) {
|
||||
if paints.iter().any(|p| paint_covers(p, n, lp, image)) && net.region_contains(i, lp) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -102,7 +104,7 @@ fn hits_node_itself(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, o
|
||||
let reach = (n.stroke.max_weight() / 2.0).max(if stroke_only { tol_l * STROKE_REACH } else { tol_l });
|
||||
path.bounding_box().inflate(reach, reach).contains(lp) && near_path(&path, lp, reach)
|
||||
}
|
||||
_ => shape_path(n).is_some_and(|path| hits_path(n, &path, lp, tol_l, !outline && is_closed(n) && fills_point(n, &path, lp))),
|
||||
_ => shape_path(n).is_some_and(|path| hits_path(n, &path, lp, tol_l, !outline && is_closed(n) && fills_point(n, &path, lp), image)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,12 +120,13 @@ fn fills_point(n: &Node, path: &BezPath, lp: Point) -> bool {
|
||||
|
||||
/// Whether local point `lp` hits `n` drawn as `path`: `inside` it (counted when it's filled, or
|
||||
/// draws nothing at all), or within reach of its outline (its stroke, else the tolerance).
|
||||
fn hits_path(n: &Node, path: &BezPath, lp: Point, tol: f64, inside: bool) -> bool {
|
||||
if inside && (n.fills.iter().any(|f| f.visible) || !n.has_visible_stroke()) {
|
||||
fn hits_path(n: &Node, path: &BezPath, lp: Point, tol: f64, inside: bool, image: ImageCoverage) -> bool {
|
||||
let filled = n.fills.iter().any(|f| f.visible);
|
||||
if inside && (if filled { fills_cover(n, lp, image) } else { !n.has_visible_stroke() }) {
|
||||
return true;
|
||||
}
|
||||
// Only a stroke with nothing filled gets the wider band: a filled shape's edge keeps the plain one.
|
||||
let stroke_only = n.has_visible_stroke() && !n.fills.iter().any(|f| f.visible);
|
||||
let stroke_only = n.has_visible_stroke() && !filled;
|
||||
let reach = (n.stroke.max_weight() / 2.0).max(if stroke_only { tol * STROKE_REACH } else { tol });
|
||||
if !path.bounding_box().inflate(reach, reach).contains(lp) {
|
||||
return false;
|
||||
@@ -131,16 +134,33 @@ fn hits_path(n: &Node, path: &BezPath, lp: Point, tol: f64, inside: bool) -> boo
|
||||
near_path(path, lp, reach)
|
||||
}
|
||||
|
||||
/// Whether a visible fill of `n` covers local point `lp`: an image fill only where its pixels show.
|
||||
fn fills_cover(n: &Node, lp: Point, image: ImageCoverage) -> bool {
|
||||
n.fills.iter().any(|f| paint_covers(f, n, lp, image))
|
||||
}
|
||||
|
||||
/// Whether paint `f` of `n` covers `lp`; an image counts as covered when `image` can't tell.
|
||||
fn paint_covers(f: &Paint, n: &Node, lp: Point, image: ImageCoverage) -> bool {
|
||||
f.visible
|
||||
&& match &f.kind {
|
||||
PaintKind::Image(p) => f.opacity > 0.0 && image.and_then(|sample| sample(p, n, lp)).unwrap_or(true),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether image paint `paint` of `n` shows local point `lp`, sampled by the caller since this crate can't decode images; `None` (no sampler, or no answer) counts as covered.
|
||||
pub type ImageCoverage<'a> = Option<&'a dyn Fn(&ImagePaint, &Node, Point) -> Option<bool>>;
|
||||
|
||||
/// A boolean group's computed result outline in its local space (filled even-odd), or `None` to
|
||||
/// hit-test its operands instead. Boolean operations live above this crate: callers that can
|
||||
/// compute results pass them in; `None` for the whole argument hit-tests operands everywhere.
|
||||
pub type BoolResult<'a> = Option<&'a dyn Fn(NodeId, &Node) -> Option<BezPath>>;
|
||||
|
||||
/// With a result for boolean group `id`, whether `pt` hits it (`None`: no result, test operands).
|
||||
fn hits_result(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, result: BoolResult, outline: bool) -> Option<bool> {
|
||||
fn hits_result(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, result: BoolResult, outline: bool, image: ImageCoverage) -> Option<bool> {
|
||||
let path = result.and_then(|f| f(id, n))?;
|
||||
let lp = doc.world_transform(id).inverse() * pt;
|
||||
Some(hits_path(n, &path, lp, tol, !outline && path.winding(lp) % 2 != 0))
|
||||
Some(hits_path(n, &path, lp, tol, !outline && path.winding(lp) % 2 != 0, image))
|
||||
}
|
||||
|
||||
fn near_path(path: &BezPath, p: Point, dist: f64) -> bool {
|
||||
@@ -151,13 +171,13 @@ fn near_path(path: &BezPath, p: Point, dist: f64) -> bool {
|
||||
/// The innermost visible, unlocked node under `pt` (page coordinates), honouring clip content;
|
||||
/// boolean groups are hit where their `result` is.
|
||||
pub fn hit_leaf(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
|
||||
hit_leaf_opts(doc, page, pt, tol, result, HitOpts::default())
|
||||
hit_leaf_opts(doc, page, pt, tol, result, HitOpts::default(), None)
|
||||
}
|
||||
|
||||
/// [`hit_leaf`] with `opts` (a deep pick reaches through unfilled nested frames, see [`HitOpts::deep`]).
|
||||
pub fn hit_leaf_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Option<NodeId> {
|
||||
/// [`hit_leaf`] with `opts` (a deep pick reaches through unfilled nested frames, see [`HitOpts::deep`]) and an `image` sampler (see [`ImageCoverage`]).
|
||||
pub fn hit_leaf_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts, image: ImageCoverage) -> Option<NodeId> {
|
||||
let p = doc.node(page)?;
|
||||
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, opts).filter(|_| !masked_out(doc, p, *c, pt)))
|
||||
p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, None, opts, image).filter(|_| !masked_out(doc, p, *c, pt)))
|
||||
}
|
||||
|
||||
/// Whether child `c` of `parent` is masked at `pt`: a visible mask below it (the nearest mask
|
||||
@@ -174,18 +194,18 @@ pub fn masked_out(doc: &Document, parent: &Node, c: NodeId, pt: Point) -> bool {
|
||||
/// Whether mask `id` draws at `pt` (its shape, or for a group or frame what its layers draw).
|
||||
fn covers(doc: &Document, id: NodeId, n: &Node, pt: Point, depth: usize) -> bool {
|
||||
depth < 512
|
||||
&& (hits_node_itself(doc, id, n, pt, 0.0, false)
|
||||
&& (hits_node_itself(doc, id, n, pt, 0.0, false, None)
|
||||
|| n.children.iter().any(|c| doc.node(*c).is_some_and(|k| k.visible && !k.is_mask && covers(doc, *c, k, pt, depth + 1))))
|
||||
}
|
||||
|
||||
/// Like [`hit_leaf`], but only within layer `root` (it included).
|
||||
pub fn hit_in(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult) -> Option<NodeId> {
|
||||
hit_in_opts(doc, root, pt, tol, result, HitOpts::default())
|
||||
hit_in_opts(doc, root, pt, tol, result, HitOpts::default(), None)
|
||||
}
|
||||
|
||||
/// [`hit_in`] with `opts` (see [`hit_leaf_opts`]).
|
||||
pub fn hit_in_opts(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Option<NodeId> {
|
||||
hit_rec(doc, root, pt, tol, 0, result, None, opts)
|
||||
pub fn hit_in_opts(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts, image: ImageCoverage) -> Option<NodeId> {
|
||||
hit_rec(doc, root, pt, tol, 0, result, None, opts, image)
|
||||
}
|
||||
|
||||
/// [`hit_leaf`] (or [`hit_in`] for a `root` that isn't a page) in outline mode: shapes are hit
|
||||
@@ -195,8 +215,8 @@ pub fn hit_in_opts(doc: &Document, root: NodeId, pt: Point, tol: f64, result: Bo
|
||||
/// when it shows them, and every layer on the edge of its box when it shows object bounds.
|
||||
pub fn hit_outlines(doc: &Document, root: NodeId, pt: Point, tol: f64, result: BoolResult, also: OutlineHits) -> Option<NodeId> {
|
||||
match doc.node(root) {
|
||||
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also), HitOpts::default())),
|
||||
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also), HitOpts::default()),
|
||||
Some(p) if p.is_page() => p.children.iter().rev().find_map(|c| hit_rec(doc, *c, pt, tol, 0, result, Some(also), HitOpts::default(), None)),
|
||||
_ => hit_rec(doc, root, pt, tol, 0, result, Some(also), HitOpts::default(), None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,14 +250,14 @@ pub struct HitOpts {
|
||||
|
||||
/// Whether `pt` hits `n` itself for a pick with `opts` ([`hits_node_itself`], but see
|
||||
/// [`HitOpts::deep`]).
|
||||
fn hits_self(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool, opts: HitOpts) -> bool {
|
||||
fn hits_self(doc: &Document, id: NodeId, n: &Node, pt: Point, tol: f64, outline: bool, opts: HitOpts, image: ImageCoverage) -> bool {
|
||||
let see_through = opts.deep
|
||||
&& !outline
|
||||
&& n.kind.is_frame_like()
|
||||
&& !n.is_board_atom()
|
||||
&& !is_board(doc, n)
|
||||
&& !n.fills.iter().any(|f| f.visible && f.opacity > 0.0);
|
||||
!see_through && hits_node_itself(doc, id, n, pt, tol, outline)
|
||||
!see_through && hits_node_itself(doc, id, n, pt, tol, outline, image)
|
||||
}
|
||||
|
||||
/// Whether `n` sits on the page or directly in a section: a top-level frame, which a pick
|
||||
@@ -255,6 +275,7 @@ fn hit_rec(
|
||||
result: BoolResult,
|
||||
also: Option<OutlineHits>,
|
||||
opts: HitOpts,
|
||||
image: ImageCoverage,
|
||||
) -> Option<NodeId> {
|
||||
if depth > 512 {
|
||||
return None;
|
||||
@@ -265,25 +286,28 @@ fn hit_rec(
|
||||
return None;
|
||||
}
|
||||
if let NodeKind::Section { contents_hidden: true } = n.kind {
|
||||
return hits_node_itself(doc, id, n, pt, tol, outline).then_some(id);
|
||||
return hits_node_itself(doc, id, n, pt, tol, outline, image).then_some(id);
|
||||
}
|
||||
let clips = n.clip && n.kind.is_frame_like();
|
||||
if clips && !hits_node_itself(doc, id, n, pt, 0.0, false) {
|
||||
// Clipping follows the frame's shape, not its image's pixels.
|
||||
if clips && !hits_node_itself(doc, id, n, pt, 0.0, false, None) {
|
||||
return None;
|
||||
}
|
||||
// A boolean group is hit where its result is (without one: where an operand is). The leaf is
|
||||
// the operand under the point, so a plain click still selects the group (see `select_target`)
|
||||
// while a deep click, a double click or a selected sibling operand reaches the operand itself.
|
||||
let in_result = if matches!(n.kind, NodeKind::BooleanOp { .. }) { hits_result(doc, id, n, pt, tol, result, outline) } else { None };
|
||||
let in_result = if matches!(n.kind, NodeKind::BooleanOp { .. }) { hits_result(doc, id, n, pt, tol, result, outline, image) } else { None };
|
||||
if in_result == Some(false) {
|
||||
return None;
|
||||
}
|
||||
for c in n.paint_order().rev() {
|
||||
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also, opts).filter(|_| !masked_out(doc, n, c, pt)) {
|
||||
if let Some(h) = hit_rec(doc, c, pt, tol, depth + 1, result, also, opts, image).filter(|_| !masked_out(doc, n, c, pt)) {
|
||||
return Some(h);
|
||||
}
|
||||
}
|
||||
if in_result == Some(true) || hits_self(doc, id, n, pt, tol, outline, opts) || also.is_some_and(|a| a.bounds) && on_box_edge(doc, id, n, pt, tol)
|
||||
if in_result == Some(true)
|
||||
|| hits_self(doc, id, n, pt, tol, outline, opts, image)
|
||||
|| also.is_some_and(|a| a.bounds) && on_box_edge(doc, id, n, pt, tol)
|
||||
{
|
||||
return Some(id);
|
||||
}
|
||||
@@ -292,7 +316,7 @@ fn hit_rec(
|
||||
|
||||
/// Every visible, unlocked layer under `pt`: [`layers_at_opts`] with the default options.
|
||||
pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult) -> Vec<(NodeId, usize)> {
|
||||
layers_at_opts(doc, page, pt, tol, result, HitOpts::default())
|
||||
layers_at_opts(doc, page, pt, tol, result, HitOpts::default(), None)
|
||||
}
|
||||
|
||||
/// Every visible layer under `pt` (page coordinates) with its depth below the page, in
|
||||
@@ -300,32 +324,51 @@ pub fn layers_at(doc: &Document, page: NodeId, pt: Point, tol: f64, result: Bool
|
||||
/// "Select layer" in the context menu lists. Locked layers are left out unless `opts.locked`.
|
||||
/// Clip content is honoured; boolean groups (hit where their `result` is) and sections with
|
||||
/// hidden contents count as one layer.
|
||||
pub fn layers_at_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result: BoolResult, opts: HitOpts) -> Vec<(NodeId, usize)> {
|
||||
fn rec(doc: &Document, id: NodeId, pt: Point, tol: f64, depth: usize, result: BoolResult, opts: HitOpts, out: &mut Vec<(NodeId, usize)>) {
|
||||
pub fn layers_at_opts(
|
||||
doc: &Document,
|
||||
page: NodeId,
|
||||
pt: Point,
|
||||
tol: f64,
|
||||
result: BoolResult,
|
||||
opts: HitOpts,
|
||||
image: ImageCoverage,
|
||||
) -> Vec<(NodeId, usize)> {
|
||||
fn rec(
|
||||
doc: &Document,
|
||||
id: NodeId,
|
||||
pt: Point,
|
||||
tol: f64,
|
||||
depth: usize,
|
||||
result: BoolResult,
|
||||
opts: HitOpts,
|
||||
image: ImageCoverage,
|
||||
out: &mut Vec<(NodeId, usize)>,
|
||||
) {
|
||||
let Some(n) = doc.node(id) else { return };
|
||||
if !n.visible || n.locked && !opts.locked || depth > 512 {
|
||||
return;
|
||||
}
|
||||
let clips = n.clip && n.kind.is_frame_like();
|
||||
if clips && !hits_node_itself(doc, id, n, pt, 0.0, false) {
|
||||
// Clipping follows the frame's shape, not its image's pixels.
|
||||
if clips && !hits_node_itself(doc, id, n, pt, 0.0, false, None) {
|
||||
return;
|
||||
}
|
||||
let at = out.len();
|
||||
let whole = matches!(n.kind, NodeKind::BooleanOp { .. } | NodeKind::Section { contents_hidden: true });
|
||||
if whole {
|
||||
if hit_rec(doc, id, pt, tol, depth, result, None, opts).is_some() {
|
||||
if hit_rec(doc, id, pt, tol, depth, result, None, opts, image).is_some() {
|
||||
out.push((id, depth));
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in n.paint_order().rev() {
|
||||
let before = out.len();
|
||||
rec(doc, c, pt, tol, depth + 1, result, opts, out);
|
||||
rec(doc, c, pt, tol, depth + 1, result, opts, image, out);
|
||||
if out.len() > before && masked_out(doc, n, c, pt) {
|
||||
out.truncate(before);
|
||||
}
|
||||
}
|
||||
if out.len() > at || hits_node_itself(doc, id, n, pt, tol, false) {
|
||||
if out.len() > at || hits_node_itself(doc, id, n, pt, tol, false, image) {
|
||||
out.insert(at, (id, depth));
|
||||
}
|
||||
}
|
||||
@@ -333,7 +376,7 @@ pub fn layers_at_opts(doc: &Document, page: NodeId, pt: Point, tol: f64, result:
|
||||
if let Some(p) = doc.node(page) {
|
||||
for c in p.children.iter().rev() {
|
||||
let before = out.len();
|
||||
rec(doc, *c, pt, tol, 0, result, opts, &mut out);
|
||||
rec(doc, *c, pt, tol, 0, result, opts, image, &mut out);
|
||||
if out.len() > before && masked_out(doc, p, *c, pt) {
|
||||
out.truncate(before);
|
||||
}
|
||||
|
||||
+49
-28
@@ -23,6 +23,7 @@ pub mod library;
|
||||
pub mod node;
|
||||
pub mod props;
|
||||
pub mod proto;
|
||||
pub mod shared;
|
||||
pub mod styles;
|
||||
pub mod text;
|
||||
pub mod vector;
|
||||
@@ -43,6 +44,7 @@ pub use handoff::*;
|
||||
pub use library::*;
|
||||
pub use node::*;
|
||||
pub use props::*;
|
||||
pub use shared::Shared;
|
||||
pub use styles::*;
|
||||
pub use text::*;
|
||||
pub use vector::*;
|
||||
@@ -54,6 +56,14 @@ use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// A walk for [`Document::world_render_bounds_with`]: how many more nodes it may visit, and how it
|
||||
/// measures each.
|
||||
struct Walk<'a> {
|
||||
left: std::cell::Cell<usize>,
|
||||
own: &'a dyn Fn(&Node, Affine) -> Option<Rect>,
|
||||
grow: &'a dyn Fn(&Node, Rect) -> Rect,
|
||||
}
|
||||
|
||||
/// Deepest descendant [`Document::world_render_bounds`] follows: as deep as the renderer draws
|
||||
/// (`figcraft_render::MAX_EXPORT_DEPTH`), so a crafted chain can't overflow the stack (#1062).
|
||||
const MAX_RENDER_DEPTH: usize = 256;
|
||||
@@ -782,53 +792,55 @@ impl Document {
|
||||
/// children only within their mask). A group, or an unclipped frame past its box, is what its
|
||||
/// children show grown by its effects, which apply to all of it.
|
||||
pub fn world_render_bounds(&self, id: NodeId) -> Option<Rect> {
|
||||
self.world_render_bounds_with(id, &|n, world| n.own_paint_bounds(world))
|
||||
self.world_render_bounds_with(id, &|n, world| Some(n.own_paint_bounds(world)), &|n, kids| n.grow_by_effects(kids))
|
||||
}
|
||||
|
||||
/// [`Document::world_render_bounds`] with what each node paints itself (its children aside)
|
||||
/// measured by `own` from the node and its world transform, for a caller that measures it more
|
||||
/// closely than [`Node::own_paint_bounds`] (an export measures the stroke itself).
|
||||
pub fn world_render_bounds_with(&self, id: NodeId, own: &dyn Fn(&Node, Affine) -> Rect) -> Option<Rect> {
|
||||
/// [`Document::world_render_bounds`] measured by the caller, for one that measures more
|
||||
/// closely than [`Node::own_paint_bounds`] (an export measures the stroke itself and frames
|
||||
/// shadows by their blur radius): `own` gives the page area a node paints itself under its
|
||||
/// world transform (its children aside), `None` for one that doesn't count, and `grow` what a
|
||||
/// group's or an unclipped frame's effects add round its children's area.
|
||||
pub fn world_render_bounds_with(
|
||||
&self,
|
||||
id: NodeId,
|
||||
own: &dyn Fn(&Node, Affine) -> Option<Rect>,
|
||||
grow: &dyn Fn(&Node, Rect) -> Rect,
|
||||
) -> Option<Rect> {
|
||||
// A tree visits each node once; a child list deserialized with repeats (a graph) is cut off
|
||||
// after twice the document's node count rather than walked in full.
|
||||
self.render_bounds_at(id, 0, &std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8)), own)
|
||||
let left = std::cell::Cell::new(self.nodes.len().saturating_mul(2).saturating_add(8));
|
||||
self.render_bounds_at(id, 0, &Walk { left, own, grow })
|
||||
}
|
||||
|
||||
fn render_bounds_at(&self, id: NodeId, depth: usize, left: &std::cell::Cell<usize>, own_paint: &dyn Fn(&Node, Affine) -> Rect) -> Option<Rect> {
|
||||
fn render_bounds_at(&self, id: NodeId, depth: usize, walk: &Walk) -> Option<Rect> {
|
||||
let n = self.node(id)?;
|
||||
let own = own_paint(n, self.world_transform(id));
|
||||
let visit = left.get();
|
||||
left.set(visit.saturating_sub(1));
|
||||
let own = (walk.own)(n, self.world_transform(id));
|
||||
let visit = walk.left.get();
|
||||
walk.left.set(visit.saturating_sub(1));
|
||||
if (n.clip && n.kind.is_frame_like() && !n.kind.bounds_follow_children()) || depth >= MAX_RENDER_DEPTH || visit == 0 {
|
||||
return Some(own);
|
||||
return own;
|
||||
}
|
||||
Some(match (self.children_render_bounds(n, depth + 1, left, own_paint), &n.kind) {
|
||||
(Some(kids), NodeKind::Group) => n.grow_by_effects(kids),
|
||||
match (self.children_render_bounds(n, depth + 1, walk), &n.kind) {
|
||||
(Some(kids), NodeKind::Group) => Some((walk.grow)(n, kids)),
|
||||
// An unclipped frame's effects apply to its children too, past its box included.
|
||||
(Some(kids), _) => own.union(n.grow_by_effects(kids)),
|
||||
(Some(kids), _) => {
|
||||
let kids = (walk.grow)(n, kids);
|
||||
Some(own.map_or(kids, |o| o.union(kids)))
|
||||
}
|
||||
(None, _) => own,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `n`'s visible children show, together: each mask's run within the mask's bounds.
|
||||
fn children_render_bounds(
|
||||
&self,
|
||||
n: &Node,
|
||||
depth: usize,
|
||||
left: &std::cell::Cell<usize>,
|
||||
own_paint: &dyn Fn(&Node, Affine) -> Rect,
|
||||
) -> Option<Rect> {
|
||||
fn children_render_bounds(&self, n: &Node, depth: usize, walk: &Walk) -> Option<Rect> {
|
||||
let shown = |i: &NodeId| self.node(*i).is_some_and(|c| c.visible && !c.is_mask);
|
||||
let mut out: Option<Rect> = None;
|
||||
for run in self.paint_runs(n) {
|
||||
let ids = n.children.get(run).unwrap_or(&[]);
|
||||
let mask = ids.first().copied().filter(|m| self.node(*m).is_some_and(|c| c.is_mask && c.visible));
|
||||
let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, left, own_paint)).reduce(|a, b| a.union(b));
|
||||
let r = ids.iter().filter(|i| shown(i)).filter_map(|i| self.render_bounds_at(*i, depth, walk)).reduce(|a, b| a.union(b));
|
||||
let r = match mask {
|
||||
Some(m) => r
|
||||
.zip(self.render_bounds_at(m, depth, left, own_paint))
|
||||
.map(|(a, b)| a.intersect(b))
|
||||
.filter(|x| x.width() > 0.0 && x.height() > 0.0),
|
||||
Some(m) => r.zip(self.render_bounds_at(m, depth, walk)).map(|(a, b)| a.intersect(b)).filter(|x| x.width() > 0.0 && x.height() > 0.0),
|
||||
None => r,
|
||||
};
|
||||
out = match (out, r) {
|
||||
@@ -978,7 +990,14 @@ impl Document {
|
||||
pt.source = m.0;
|
||||
}
|
||||
}
|
||||
if let NodeKind::Vector { network } = &mut c.kind {
|
||||
if let NodeKind::Vector { network } = &mut c.kind
|
||||
&& network
|
||||
.regions
|
||||
.iter()
|
||||
.filter_map(|r| r.fills.as_deref())
|
||||
.flatten()
|
||||
.any(|p| matches!(&p.kind, figcraft_color::PaintKind::Pattern(pt) if map.contains_key(&NodeId(pt.source))))
|
||||
{
|
||||
for p in network.regions.iter_mut().filter_map(|r| r.fills.as_mut()).flatten() {
|
||||
if let figcraft_color::PaintKind::Pattern(pt) = &mut p.kind
|
||||
&& let Some(m) = map.get(&NodeId(pt.source))
|
||||
@@ -1379,6 +1398,8 @@ mod proto_expr_tests;
|
||||
#[cfg(test)]
|
||||
mod proto_overlay_anchor_tests;
|
||||
#[cfg(test)]
|
||||
mod shared_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod vector_radius_tests;
|
||||
|
||||
+51
-10
@@ -6,6 +6,7 @@ use crate::props::{
|
||||
StrokeProps,
|
||||
};
|
||||
use crate::proto::{Interaction, Overflow, ScrollPosition};
|
||||
use crate::shared::Shared;
|
||||
use crate::styles::{CollectionId, ModeId, StyleRefs, VariableId};
|
||||
use crate::text::TextData;
|
||||
use crate::vector::VectorNetwork;
|
||||
@@ -78,9 +79,6 @@ pub fn ordered_props<'a>(props: &'a BTreeMap<String, PropDef>, order: &[String])
|
||||
}
|
||||
|
||||
/// What a node is, with per-type data.
|
||||
// Text sets the size; the lint counts the gap to the next largest variant, which grew only because
|
||||
// Page's guides moved to the node (#1476).
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum NodeKind {
|
||||
@@ -120,9 +118,9 @@ pub enum NodeKind {
|
||||
},
|
||||
Line,
|
||||
Vector {
|
||||
network: VectorNetwork,
|
||||
network: Shared<VectorNetwork>,
|
||||
},
|
||||
Text(TextData),
|
||||
Text(Shared<TextData>),
|
||||
BooleanOp {
|
||||
op: BoolOp,
|
||||
},
|
||||
@@ -241,7 +239,7 @@ pub struct Annotation {
|
||||
/// (`figcraft_engine::code_connect`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CodeLink {
|
||||
/// `react`, `leptos`, `vue`, `swiftui`, `compose`, `arkui` or `flutter`.
|
||||
/// `react`, `leptos`, `vue`, `swiftui`, `compose`, `arkui`, `flutter` or `raw`.
|
||||
pub language: String,
|
||||
/// What the snippet imports from (`@acme/ui`, a Swift module, a Kotlin name).
|
||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||
@@ -721,7 +719,7 @@ impl Node {
|
||||
let blend = if kind.is_container() { BlendMode::PassThrough } else { BlendMode::Normal };
|
||||
let clip = matches!(kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. } | NodeKind::Instance { .. });
|
||||
let corners = match &kind {
|
||||
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], smoothing: 0.0 },
|
||||
NodeKind::ComponentSet { .. } => Corners { radii: [5.0; 4], ..Corners::default() },
|
||||
_ => Corners::default(),
|
||||
};
|
||||
Self {
|
||||
@@ -804,6 +802,23 @@ impl Node {
|
||||
self.board.as_ref().is_some_and(crate::BoardItem::is_atom)
|
||||
}
|
||||
|
||||
/// Whether this layer puts nothing on the canvas: no visible fill (its own, a vector
|
||||
/// region's or a text run's), stroke or effect and no children (a placeholder box whose image was taken out,
|
||||
/// an empty frame).
|
||||
pub fn draws_nothing(&self) -> bool {
|
||||
let shows = |f: &Option<Vec<Paint>>| f.as_deref().is_some_and(|f| f.iter().any(|p| p.visible));
|
||||
let region_fill = match &self.kind {
|
||||
NodeKind::Vector { network } => network.regions.iter().any(|r| shows(&r.fills)),
|
||||
NodeKind::Text(t) => shows(&t.style.fills) || t.runs.iter().any(|r| shows(&r.style.fills)),
|
||||
_ => false,
|
||||
};
|
||||
self.children.is_empty()
|
||||
&& !self.fills.iter().any(|f| f.visible)
|
||||
&& !region_fill
|
||||
&& !self.has_visible_stroke()
|
||||
&& !self.effects.iter().any(|e| e.visible)
|
||||
}
|
||||
|
||||
/// A section whose contents are hidden: only its name and outline show; its children are
|
||||
/// skipped when rendering and hit testing.
|
||||
pub fn hides_contents(&self) -> bool {
|
||||
@@ -910,9 +925,21 @@ impl Node {
|
||||
/// The page-space area this node paints itself under `world` (its children aside): its box
|
||||
/// grown by its strokes and glyphs, then by its effects (see [`Node::grow_by_effects`]).
|
||||
pub fn own_paint_bounds(&self, world: Affine) -> figcraft_geom::Rect {
|
||||
self.own_bounds_with(world, SHADOW_BLUR_REACH)
|
||||
}
|
||||
|
||||
/// [`Node::own_paint_bounds`] as an export frames it: drop shadows count as far as their blur
|
||||
/// radius (what the reference tool's exports and render bounds take in; the faint tail of the
|
||||
/// blur past it stays out).
|
||||
pub fn own_export_bounds(&self, world: Affine) -> figcraft_geom::Rect {
|
||||
self.own_bounds_with(world, 1.0)
|
||||
}
|
||||
|
||||
/// [`Node::own_paint_bounds`] with drop shadows' blur reaching `blur` times their radius.
|
||||
fn own_bounds_with(&self, world: Affine, blur: f64) -> figcraft_geom::Rect {
|
||||
let o = self.outline_reach();
|
||||
let base = self.local_rect().inflate(o, o);
|
||||
let grown = self.grow_by_effects(figcraft_geom::transform_rect_bbox(world, base));
|
||||
let grown = self.grow_by_effects_with(figcraft_geom::transform_rect_bbox(world, base), blur);
|
||||
// A filled outline's spread grows in local units (see [`Node::outline_spreads`]): a box by
|
||||
// its spread all round, sharp corners' mitres anywhere within a circle of it.
|
||||
let [a, b, c, d, _, _] = world.as_coeffs();
|
||||
@@ -926,7 +953,7 @@ impl Node {
|
||||
let m = spread * SPREAD_MITER_LIMIT;
|
||||
figcraft_geom::transform_rect_bbox(world, base).inflate(m * a.hypot(c), m * b.hypot(d))
|
||||
};
|
||||
let (g, (dx, dy)) = (layer + s.radius.abs() * 1.5, s.offset);
|
||||
let (g, (dx, dy)) = (layer + s.radius.abs() * blur, s.offset);
|
||||
if g.is_finite() && dx.is_finite() && dy.is_finite() && outline.is_finite() {
|
||||
r.union(outline.inflate(g, g) + figcraft_geom::kurbo::Vec2::new(dx, dy))
|
||||
} else {
|
||||
@@ -943,12 +970,22 @@ impl Node {
|
||||
/// Layer blurs and texture grow it by what they reach together, and drop shadows are cast from
|
||||
/// that (see [`Node::layer_effects_reach`]).
|
||||
pub fn grow_by_effects(&self, b: figcraft_geom::Rect) -> figcraft_geom::Rect {
|
||||
self.grow_by_effects_with(b, SHADOW_BLUR_REACH)
|
||||
}
|
||||
|
||||
/// [`Node::grow_by_effects`] as an export frames it (see [`Node::own_export_bounds`]).
|
||||
pub fn grow_by_export_effects(&self, b: figcraft_geom::Rect) -> figcraft_geom::Rect {
|
||||
self.grow_by_effects_with(b, 1.0)
|
||||
}
|
||||
|
||||
/// [`Node::grow_by_effects`] with drop shadows' blur reaching `blur` times their radius.
|
||||
fn grow_by_effects_with(&self, b: figcraft_geom::Rect, blur: f64) -> figcraft_geom::Rect {
|
||||
let miter = self.spread_miter_reach();
|
||||
let layer = self.layer_effects_reach();
|
||||
let moved = if layer > 0.0 { b.inflate(layer, layer) } else { b };
|
||||
self.effects.iter().filter(|e| e.visible).fold(moved, |r, e| match &e.kind {
|
||||
EffectKind::DropShadow(s) => {
|
||||
let g = s.radius.abs() * 1.5 + s.spread.max(0.0) + miter;
|
||||
let g = s.radius.abs() * blur + s.spread.max(0.0) + miter;
|
||||
let (dx, dy) = s.offset;
|
||||
if g.is_finite() && dx.is_finite() && dy.is_finite() {
|
||||
r.union(moved.inflate(g, g) + figcraft_geom::kurbo::Vec2::new(dx, dy))
|
||||
@@ -1040,6 +1077,10 @@ impl Node {
|
||||
/// canvas, and a sum of any number of them (or of their squares) stays finite.
|
||||
const MAX_EFFECT_REACH: f64 = 1e100;
|
||||
|
||||
/// How many times its radius a drop shadow's blur reaches past the shape when everything it paints
|
||||
/// counts: three standard deviations of a blur whose deviation is half the radius.
|
||||
const SHADOW_BLUR_REACH: f64 = 1.5;
|
||||
|
||||
/// An effect's reach made safe to add: finite, in 0..[`MAX_EFFECT_REACH`].
|
||||
fn effect_reach(r: f64) -> f64 {
|
||||
if r.is_finite() { r.clamp(0.0, MAX_EFFECT_REACH) } else { 0.0 }
|
||||
|
||||
@@ -1004,6 +1004,8 @@ impl Effect {
|
||||
pub struct Corners {
|
||||
pub radii: [f64; 4],
|
||||
pub smoothing: f64,
|
||||
#[serde(skip_serializing_if = "figcraft_geom::CornerStyle::is_round")]
|
||||
pub style: figcraft_geom::CornerStyle,
|
||||
}
|
||||
|
||||
impl Corners {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Copy-on-write `Arc` wrapper for shared layer payloads (`TextData`, `VectorNetwork`).
|
||||
//!
|
||||
//! Cloning a [`Shared`] payload is an O(1) atomic reference-count bump, so mirrored layers inside
|
||||
//! component instances and duplicated subtrees share identical vector networks and text data in
|
||||
//! memory. Mutating through [`DerefMut`] detaches via [`Arc::make_mut`], leaving every other
|
||||
//! holder unchanged. Serialization and deserialization are transparent.
|
||||
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
|
||||
/// Copy-on-write reference-counted wrapper around `T`.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Shared<T>(Arc<T>);
|
||||
|
||||
impl<T> Shared<T> {
|
||||
/// Wrap `value` in a new shared allocation.
|
||||
pub fn new(value: T) -> Self {
|
||||
Self(Arc::new(value))
|
||||
}
|
||||
|
||||
/// Wrap an existing [`Arc`].
|
||||
pub fn from_arc(arc: Arc<T>) -> Self {
|
||||
Self(arc)
|
||||
}
|
||||
|
||||
/// Borrow the underlying [`Arc`].
|
||||
pub fn as_arc(&self) -> &Arc<T> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// Unwrap the underlying [`Arc`].
|
||||
pub fn into_arc(self) -> Arc<T> {
|
||||
self.0
|
||||
}
|
||||
|
||||
/// Whether `self` and `other` point to the exact same allocation.
|
||||
pub fn ptr_eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.0, &other.0)
|
||||
}
|
||||
|
||||
/// Current strong reference count of the underlying allocation.
|
||||
pub fn strong_count(&self) -> usize {
|
||||
Arc::strong_count(&self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Shared<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(Arc::clone(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Shared<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> DerefMut for Shared<T> {
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
Arc::make_mut(&mut self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for Shared<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
*self.0 == *other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Eq> Eq for Shared<T> {}
|
||||
|
||||
impl<T> From<T> for Shared<T> {
|
||||
fn from(value: T) -> Self {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<Arc<T>> for Shared<T> {
|
||||
fn from(arc: Arc<T>) -> Self {
|
||||
Self(arc)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> AsRef<T> for Shared<T> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Serialize> Serialize for Shared<T> {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
self.0.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T: Deserialize<'de>> Deserialize<'de> for Shared<T> {
|
||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
T::deserialize(deserializer).map(Self::new)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
//! Copy-on-write structural sharing tests for [`Shared`] and `NodeKind` payloads.
|
||||
|
||||
use figcraft_geom::Point;
|
||||
|
||||
use crate::*;
|
||||
|
||||
#[test]
|
||||
fn node_kind_stays_compact_with_shared_text_and_vector_payloads() {
|
||||
use std::mem::size_of;
|
||||
// Before wrapping TextData (352 B) and VectorNetwork (72 B) in Shared<T>, NodeKind was 352 B
|
||||
// and Node was 1608 B.
|
||||
assert!(size_of::<NodeKind>() <= 144, "NodeKind grew unexpectedly: {} bytes", size_of::<NodeKind>());
|
||||
assert!(size_of::<Node>() <= 1400, "Node grew unexpectedly: {} bytes", size_of::<Node>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_clone_shares_pointer_and_deref_mut_detaches_without_mutating_source() {
|
||||
let mut net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0)], true);
|
||||
let a = Shared::new(net.clone());
|
||||
let mut b = a.clone();
|
||||
assert!(a.ptr_eq(&b));
|
||||
assert_eq!(a.strong_count(), 2);
|
||||
|
||||
// Mutating through DerefMut detaches b and leaves a untouched.
|
||||
b.vertices[0].x = 42.0;
|
||||
assert!(!a.ptr_eq(&b));
|
||||
assert_eq!(a.strong_count(), 1);
|
||||
assert_eq!(b.strong_count(), 1);
|
||||
assert_eq!(a.vertices[0].x, 0.0);
|
||||
assert_eq!(b.vertices[0].x, 42.0);
|
||||
|
||||
// Non-mutating reads never detach.
|
||||
net.vertices[0].x = 42.0;
|
||||
assert_eq!(*b, net);
|
||||
let c = b.clone();
|
||||
let _len = c.vertices.len();
|
||||
assert!(b.ptr_eq(&c));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicated_text_and_vector_layers_share_payloads_until_edited() {
|
||||
let mut doc = Document::new("CoW");
|
||||
let page = doc.first_page().unwrap();
|
||||
let group = doc.create(page, NodeKind::Frame, "Card", 0.0, 0.0, 200.0, 100.0).unwrap();
|
||||
let net = VectorNetwork::from_points(&[Point::new(0.0, 0.0), Point::new(24.0, 0.0), Point::new(12.0, 24.0)], true);
|
||||
let vec_id = doc.create(group, NodeKind::Vector { network: net.into() }, "Icon", 0.0, 0.0, 24.0, 24.0).unwrap();
|
||||
let txt_id = doc.create(group, NodeKind::Text(TextData::new("Hello").into()), "Title", 32.0, 0.0, 100.0, 20.0).unwrap();
|
||||
|
||||
let copy = doc.duplicate_into(group, page, None).unwrap();
|
||||
let copy_children = doc.node(copy).unwrap().children.clone();
|
||||
let (copy_vec, copy_txt) = (copy_children[0], copy_children[1]);
|
||||
|
||||
// Both vector and text payloads share the exact same Arc right after duplication.
|
||||
match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) {
|
||||
(NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)),
|
||||
_ => panic!("expected vector nodes"),
|
||||
}
|
||||
match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) {
|
||||
(NodeKind::Text(a), NodeKind::Text(b)) => assert!(a.ptr_eq(b)),
|
||||
_ => panic!("expected text nodes"),
|
||||
}
|
||||
|
||||
// Editing the copy's text detaches only the copy's TextData; the vector stays shared.
|
||||
if let Some(NodeKind::Text(t)) = doc.node_mut(copy_txt).map(|n| &mut n.kind) {
|
||||
t.characters = "Edited".into();
|
||||
}
|
||||
match (&doc.node(txt_id).unwrap().kind, &doc.node(copy_txt).unwrap().kind) {
|
||||
(NodeKind::Text(a), NodeKind::Text(b)) => {
|
||||
assert!(!a.ptr_eq(b));
|
||||
assert_eq!(a.characters, "Hello");
|
||||
assert_eq!(b.characters, "Edited");
|
||||
}
|
||||
_ => panic!("expected text nodes"),
|
||||
}
|
||||
match (&doc.node(vec_id).unwrap().kind, &doc.node(copy_vec).unwrap().kind) {
|
||||
(NodeKind::Vector { network: a }, NodeKind::Vector { network: b }) => assert!(a.ptr_eq(b)),
|
||||
_ => panic!("expected vector nodes"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_serialization_is_transparent_in_json() {
|
||||
let td = TextData::new("Transparent");
|
||||
let raw = serde_json::to_string(&td).unwrap();
|
||||
let wrapped = serde_json::to_string(&Shared::new(td.clone())).unwrap();
|
||||
assert_eq!(raw, wrapped);
|
||||
let back: Shared<TextData> = serde_json::from_str(&wrapped).unwrap();
|
||||
assert_eq!(*back, td);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "benchmark: run with cargo test --release -p figcraft-doc bench_cow_sharing -- --ignored --nocapture"]
|
||||
fn bench_cow_sharing() {
|
||||
use std::collections::HashSet;
|
||||
use std::mem::size_of;
|
||||
use std::time::Instant;
|
||||
|
||||
let pts: Vec<Point> = (0..64)
|
||||
.map(|i| {
|
||||
let a = (i as f64) * std::f64::consts::TAU / 64.0;
|
||||
let r = if i % 2 == 0 { 16.0 } else { 8.0 };
|
||||
Point::new(a.cos() * r, a.sin() * r)
|
||||
})
|
||||
.collect();
|
||||
let icon = VectorNetwork::from_points(&pts, true);
|
||||
|
||||
let mut doc = Document::new("BenchCoW");
|
||||
let page = doc.first_page().unwrap();
|
||||
let comp = doc
|
||||
.create(
|
||||
page,
|
||||
NodeKind::Component { description: "Card".into(), props: Default::default(), prop_order: Vec::new() },
|
||||
"Card",
|
||||
0.0,
|
||||
0.0,
|
||||
400.0,
|
||||
300.0,
|
||||
)
|
||||
.unwrap();
|
||||
let mut kids = Vec::new();
|
||||
for i in 0..40 {
|
||||
let kind = match i % 4 {
|
||||
0 => NodeKind::Text(TextData::new(format!("Label {i}")).into()),
|
||||
1 => NodeKind::Vector { network: icon.clone().into() },
|
||||
_ => NodeKind::Rectangle,
|
||||
};
|
||||
kids.push(doc.create(comp, kind, &format!("L{i}"), (i % 8) as f64 * 48.0, (i / 8) as f64 * 56.0, 40.0, 40.0).unwrap());
|
||||
}
|
||||
|
||||
let t0 = Instant::now();
|
||||
for k in 0..1024 {
|
||||
let inst = doc
|
||||
.create(
|
||||
page,
|
||||
NodeKind::Instance { component: comp, props: Default::default() },
|
||||
"Card",
|
||||
(k % 32) as f64 * 420.0,
|
||||
(k / 32) as f64 * 320.0,
|
||||
400.0,
|
||||
300.0,
|
||||
)
|
||||
.unwrap();
|
||||
doc.get_mut(inst).unwrap().source = Some(comp);
|
||||
for &src_id in &kids {
|
||||
let mut c = doc.node(src_id).unwrap().clone();
|
||||
c.id = doc.alloc_id();
|
||||
c.parent = None;
|
||||
c.children.clear();
|
||||
c.source = Some(src_id);
|
||||
doc.insert(c, inst, None).unwrap();
|
||||
}
|
||||
}
|
||||
let build_ms = t0.elapsed().as_secs_f64() * 1000.0;
|
||||
|
||||
let mut unique_vec_ptrs = HashSet::new();
|
||||
let mut unique_txt_ptrs = HashSet::new();
|
||||
let mut total_vecs = 0usize;
|
||||
let mut total_txts = 0usize;
|
||||
for n in doc.nodes() {
|
||||
match &n.kind {
|
||||
NodeKind::Vector { network } => {
|
||||
total_vecs += 1;
|
||||
unique_vec_ptrs.insert(std::sync::Arc::as_ptr(network.as_arc()) as usize);
|
||||
}
|
||||
NodeKind::Text(t) => {
|
||||
total_txts += 1;
|
||||
unique_txt_ptrs.insert(std::sync::Arc::as_ptr(t.as_arc()) as usize);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let vec_heap_one = icon.vertices.len() * size_of::<Vertex>()
|
||||
+ icon.segments.len() * size_of::<Segment>()
|
||||
+ icon.regions.len() * size_of::<Region>()
|
||||
+ icon.regions.iter().map(|r| r.loops.iter().map(|l| l.len() * size_of::<usize>()).sum::<usize>()).sum::<usize>();
|
||||
let vec_heap_naive = total_vecs * vec_heap_one;
|
||||
let vec_heap_shared = unique_vec_ptrs.len() * vec_heap_one;
|
||||
|
||||
eprintln!(
|
||||
"Node={} B (was 1608 B), NodeKind={} B (was 352 B)\n42k build: {:.1} ms, nodes={}\nVectors: {} total -> {} unique Arcs (heap {:.2} MB -> {:.3} MB, {:.1}x)\nTexts: {} total -> {} unique Arcs ({:.1}x)",
|
||||
size_of::<Node>(),
|
||||
size_of::<NodeKind>(),
|
||||
build_ms,
|
||||
doc.node_count(),
|
||||
total_vecs,
|
||||
unique_vec_ptrs.len(),
|
||||
vec_heap_naive as f64 / 1_048_576.0,
|
||||
vec_heap_shared as f64 / 1_048_576.0,
|
||||
vec_heap_naive as f64 / vec_heap_shared.max(1) as f64,
|
||||
total_txts,
|
||||
unique_txt_ptrs.len(),
|
||||
total_txts as f64 / unique_txt_ptrs.len().max(1) as f64,
|
||||
);
|
||||
}
|
||||
+19
-5
@@ -137,7 +137,7 @@ fn region_paints_participate_in_colors_images_and_pattern_remapping() {
|
||||
figcraft_color::Paint::image("region-image", figcraft_color::ImageScaleMode::Fill),
|
||||
figcraft_color::Paint::pattern(source.0),
|
||||
]);
|
||||
let vector = d.create(group, NodeKind::Vector { network }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap();
|
||||
let vector = d.create(group, NodeKind::Vector { network: network.into() }, "Vector", 0.0, 0.0, 20.0, 20.0).unwrap();
|
||||
assert!(used_images(&d).contains("region-image"));
|
||||
let dup = d.duplicate_into(group, p, None).unwrap();
|
||||
let copied_children = d.node(dup).unwrap().children.clone();
|
||||
@@ -305,13 +305,27 @@ fn collections_and_modes_resolve_stored_ids_never_by_name() {
|
||||
assert_eq!(theme.find_mode("Dark").map(|m| m.id.as_str()), Some("m2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_style_roundtrips_and_old_radii_default_to_round() {
|
||||
use figcraft_geom::CornerStyle;
|
||||
let legacy = serde_json::json!({"radii": [2.0, 4.0, 6.0, 8.0], "smoothing": 0.4});
|
||||
let mut corners: crate::Corners = serde_json::from_value(legacy.clone()).unwrap();
|
||||
assert_eq!(corners.style, CornerStyle::Round);
|
||||
assert_eq!(serde_json::to_value(corners).unwrap(), legacy);
|
||||
for style in [CornerStyle::Chamfer, CornerStyle::Concave] {
|
||||
corners.style = style;
|
||||
let saved = serde_json::to_value(corners).unwrap();
|
||||
assert_eq!(serde_json::from_value::<crate::Corners>(saved).unwrap(), corners);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_roundtrip_and_repair() {
|
||||
let mut d = Document::new("x");
|
||||
let p = page(&d);
|
||||
let f = d.create(p, NodeKind::Frame, "F", 0.0, 0.0, 100.0, 100.0).unwrap();
|
||||
d.get_mut(f).unwrap().layout = Some(AutoLayout::default());
|
||||
d.create(f, NodeKind::Text(TextData::new("Hi")), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
d.create(f, NodeKind::Text(TextData::new("Hi").into()), "Hi", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
d.create(f, NodeKind::Star { count: 5, inner_ratio: 0.4 }, "S", 0.0, 0.0, 10.0, 10.0).unwrap();
|
||||
let j = serde_json::to_string(&d).unwrap();
|
||||
let back: Document = serde_json::from_str(&j).unwrap();
|
||||
@@ -576,12 +590,12 @@ fn hit_test_even_odd_vector_hole_misses() {
|
||||
};
|
||||
let mut d = Document::new("x");
|
||||
let p = page(&d);
|
||||
let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
|
||||
let eo = d.create(p, NodeKind::Vector { network: ring(WindingRule::EvenOdd).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
|
||||
assert_eq!(d.hit_test(p, Point::new(20.0, 100.0), 0.0, None), Some(eo));
|
||||
assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), None, "the hole is not filled");
|
||||
let mut d = Document::new("x");
|
||||
let p = page(&d);
|
||||
let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero) }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
|
||||
let nz = d.create(p, NodeKind::Vector { network: ring(WindingRule::NonZero).into() }, "V", 0.0, 0.0, 200.0, 200.0).unwrap();
|
||||
assert_eq!(d.hit_test(p, Point::new(100.0, 100.0), 0.0, None), Some(nz));
|
||||
}
|
||||
|
||||
@@ -832,7 +846,7 @@ fn clicks_on_a_smoothed_vector_corner_follow_the_drawn_fill() {
|
||||
let smoothed = net.rounded_smoothed(1.0).unwrap();
|
||||
let mut d = Document::new("x");
|
||||
let p = page(&d);
|
||||
let v = d.create(p, NodeKind::Vector { network: net.clone() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap();
|
||||
let v = d.create(p, NodeKind::Vector { network: net.clone().into() }, "V", 0.0, 0.0, 1000.0, 1000.0).unwrap();
|
||||
let n = d.node_mut(v).unwrap();
|
||||
n.corners.smoothing = 1.0;
|
||||
n.strokes.clear();
|
||||
|
||||
+48
-3
@@ -114,6 +114,17 @@ pub enum TextCase {
|
||||
SmallCaps,
|
||||
}
|
||||
|
||||
/// Where characters sit on the line: superscript (smaller and raised) or subscript (smaller and
|
||||
/// lowered), drawn with the font's `sups` / `subs` glyphs or synthesised without them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum TextPosition {
|
||||
#[default]
|
||||
None,
|
||||
Superscript,
|
||||
Subscript,
|
||||
}
|
||||
|
||||
impl TextCase {
|
||||
pub fn apply(self, s: &str) -> String {
|
||||
self.apply_after(s, None)
|
||||
@@ -339,6 +350,9 @@ pub struct TextStyle {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub decoration_look: Option<Box<DecorationLook>>,
|
||||
pub case: TextCase,
|
||||
/// Superscript or subscript for these chars; `None` leaves the layer's `sups` / `subs`.
|
||||
#[serde(skip_serializing_if = "crate::node::is_default")]
|
||||
pub position: TextPosition,
|
||||
/// Run fills (None = node fills).
|
||||
pub fills: Option<Vec<Paint>>,
|
||||
/// Hyperlink.
|
||||
@@ -391,6 +405,7 @@ impl Default for TextStyle {
|
||||
decoration: TextDecoration::None,
|
||||
decoration_look: None,
|
||||
case: TextCase::Original,
|
||||
position: TextPosition::None,
|
||||
fills: None,
|
||||
link: None,
|
||||
variations: std::collections::BTreeMap::new(),
|
||||
@@ -416,10 +431,12 @@ impl TextStyle {
|
||||
|| self.variations.get("slnt").is_some_and(|v| *v != 0.0)
|
||||
}
|
||||
|
||||
/// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case
|
||||
/// and axis values) and link to it as `id`; fills and hyperlinks stay.
|
||||
/// Take what text style `def` sets (font, size, line height, letter spacing, decoration, case,
|
||||
/// a position when it has one, and axis values) and link to it as `id`; fills, hyperlinks and
|
||||
/// a position the style doesn't set stay.
|
||||
pub fn take_text_style(&mut self, def: &TextStyle, id: &str) {
|
||||
*self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), ..def.clone() };
|
||||
let position = if def.position == TextPosition::None { self.position } else { def.position };
|
||||
*self = TextStyle { fills: self.fills.take(), link: self.link.take(), style_id: Some(id.to_string()), position, ..def.clone() };
|
||||
}
|
||||
|
||||
/// Whether these chars show what text style `def` sets.
|
||||
@@ -432,6 +449,7 @@ impl TextStyle {
|
||||
&& self.decoration == def.decoration
|
||||
&& self.decoration_look == def.decoration_look
|
||||
&& self.case == def.case
|
||||
&& (def.position == TextPosition::None || self.position == def.position)
|
||||
&& self.variations == def.variations
|
||||
}
|
||||
|
||||
@@ -719,6 +737,33 @@ impl TextData {
|
||||
};
|
||||
}
|
||||
|
||||
/// Where chars styled `s` sit: their own position, else the layer's `sups` / `subs` (`sups`
|
||||
/// first, as drawn).
|
||||
pub fn position_of(&self, s: &TextStyle) -> TextPosition {
|
||||
let on = |tag: &str| self.features.get(tag).copied().unwrap_or(false);
|
||||
match s.position {
|
||||
TextPosition::None if on("sups") => TextPosition::Superscript,
|
||||
TextPosition::None if on("subs") => TextPosition::Subscript,
|
||||
p => p,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set chars `start..end` to `position`. The layer's `sups` / `subs` move onto its chars
|
||||
/// first, so a range set to none is drawn on the line.
|
||||
pub fn set_position(&mut self, start: usize, end: usize, position: TextPosition) {
|
||||
let layer = self.position_of(&TextStyle::default());
|
||||
self.features.remove("sups");
|
||||
self.features.remove("subs");
|
||||
if layer != TextPosition::None {
|
||||
self.restyle(0, self.char_count(), |s| {
|
||||
if s.position == TextPosition::None {
|
||||
s.position = layer;
|
||||
}
|
||||
});
|
||||
}
|
||||
self.restyle(start, end, |s| s.position = position);
|
||||
}
|
||||
|
||||
/// The style at char index `i`.
|
||||
pub fn style_at(&self, i: usize) -> &TextStyle {
|
||||
self.runs.iter().find(|r| r.start <= i && i < r.end).map(|r| &r.style).unwrap_or(&self.style)
|
||||
|
||||
@@ -25,6 +25,8 @@ craft-docpath = { workspace = true }
|
||||
figcraft-plugin = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
# `clock`: the local UTC offset handed to plugins (craft-i18n already enables it, wasmbind too).
|
||||
chrono = { workspace = true, features = ["clock"] }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
@@ -43,3 +45,5 @@ craft-font-catalog = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
wat = { workspace = true }
|
||||
image = { workspace = true }
|
||||
# Writes the DNG files the camera raw tests open.
|
||||
craft-raw = { workspace = true }
|
||||
@@ -125,6 +125,34 @@ fn fill_along_a_hugging_parent_notes_that_the_width_is_fixed() {
|
||||
assert_eq!(s.message, None);
|
||||
}
|
||||
|
||||
/// #2178: through the API, the sizing an edit changes on another layer comes back in `warnings`
|
||||
/// (the canvas shows it as a notice), naming that layer; an edit that changes no other layer's
|
||||
/// sizing has none.
|
||||
#[test]
|
||||
fn node_set_warns_about_the_other_layers_it_turns_fixed() {
|
||||
let mut s = Session::new();
|
||||
let root = al_frame(&mut s, json!({"sizingH": "hug", "sizingV": "hug"}));
|
||||
let menu = rect(&mut s, root, 200.0, 100.0, "#222222");
|
||||
let content = rect(&mut s, root, 600.0, 900.0, "#FFFFFF");
|
||||
let warnings = |v: Value| v["warnings"].as_array().cloned().unwrap_or_default();
|
||||
let names = |w: &[Value], n: NodeId, key: &str| w.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with(&format!("{n} ")) && w.contains(key)));
|
||||
|
||||
let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingV": "fill"}})).unwrap());
|
||||
assert!(w.is_empty(), "a non-Fill sibling is left, the root keeps hugging: {w:?}");
|
||||
let w = warnings(s.execute("node.set", &json!({"id": content, "props": {"sizingV": "fill"}})).unwrap());
|
||||
assert_eq!(sizing(&s, root).1, Sizing::Fixed);
|
||||
assert!(names(&w, root, "sizingV"), "the root turned Fixed: {w:?}");
|
||||
assert!(!names(&w, content, "sizingV"), "not the layer edited: {w:?}");
|
||||
|
||||
// Along the row: the menu filling its width turns the root's width Fixed; hugging it again
|
||||
// turns the menu's width Fixed.
|
||||
let w = warnings(s.execute("node.set", &json!({"id": menu, "props": {"sizingH": "fill"}})).unwrap());
|
||||
assert!(names(&w, root, "sizingH"), "{w:?}");
|
||||
let w = warnings(s.execute("node.set", &json!({"id": root, "props": {"sizingH": "hug"}})).unwrap());
|
||||
assert_eq!(sizing(&s, menu).0, Sizing::Fixed);
|
||||
assert!(names(&w, menu, "sizingH") && !names(&w, root, "sizingH"), "the child that filled it: {w:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hugging_a_row_notes_the_child_that_filled_its_width_turned_fixed() {
|
||||
let mut s = Session::new();
|
||||
@@ -458,6 +486,275 @@ fn auto_layout_keys_beside_no_auto_layout_are_refused() {
|
||||
assert!(s.doc().unwrap().node(f).unwrap().layout.is_none());
|
||||
}
|
||||
|
||||
// ---- Add auto layout (Shift+A) defaults, measured in Figma's web app with synthetic rectangles ----
|
||||
|
||||
fn rect_at(s: &mut Session, parent: Option<NodeId>, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
let mut p = json!({"x": x, "y": y, "width": w, "height": h});
|
||||
if let (Some(parent), Some(o)) = (parent, p.as_object_mut()) {
|
||||
o.insert("parent".into(), json!(parent));
|
||||
}
|
||||
id(s.execute("shape.rectangle", &p).unwrap())
|
||||
}
|
||||
|
||||
fn add_layout(s: &mut Session, ids: &[NodeId]) -> NodeId {
|
||||
let r = s.execute("layout.add", &json!({"ids": ids})).unwrap();
|
||||
id_of(&r["ids"][0]).unwrap()
|
||||
}
|
||||
|
||||
fn canvas(s: &Session, node: NodeId) -> (f64, f64) {
|
||||
let c = s.doc().unwrap().world_transform(node).as_coeffs();
|
||||
(c[4], c[5])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_two_rects_far_apart_spaces_them_between_at_a_fixed_width() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.main_align, l.padding), (LayoutMode::Horizontal, MainAlign::SpaceBetween, [0.0; 4]));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (140.0, 40.0));
|
||||
assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_gap_auto_needs_a_gap_at_least_the_narrower_child() {
|
||||
// (first size, second x, second width, second height, Auto?)
|
||||
for (w, x2, w2, h2, auto) in [
|
||||
(40.0, 72.0, 40.0, 40.0, false),
|
||||
(40.0, 80.0, 40.0, 40.0, true),
|
||||
(20.0, 52.0, 20.0, 20.0, true),
|
||||
(100.0, 160.0, 100.0, 100.0, false),
|
||||
(40.0, 100.0, 80.0, 60.0, true),
|
||||
] {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, w, w);
|
||||
let b = rect_at(&mut s, None, x2, 0.0, w2, h2);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!(l.gap, x2 - w, "{w} {x2}");
|
||||
if auto {
|
||||
assert_eq!((l.main_align, n.child_layout.sizing_h, n.width), (MainAlign::SpaceBetween, Sizing::Fixed, x2 + w2), "{w} {x2}");
|
||||
} else {
|
||||
assert_eq!(l.main_align, MainAlign::Min, "{w} {x2}");
|
||||
assert_eq!(n.child_layout.sizing_h, Sizing::Hug, "{w} {x2}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_three_rects_in_a_row_uses_the_mean_gap_and_hugs() {
|
||||
for (xs, gap, width) in [([0.0, 100.0, 200.0], 60.0, 240.0), ([0.0, 100.0, 180.0], 50.0, 220.0)] {
|
||||
let mut s = Session::new();
|
||||
let ids: Vec<NodeId> = xs.iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect();
|
||||
let f = add_layout(&mut s, &ids);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!(l.gap, gap);
|
||||
assert_eq!(l.main_align, MainAlign::Min);
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Hug, Sizing::Hug, width));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_stacked_rects_fixes_the_width_and_hugs_the_height() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 60.0));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (80.0, 160.0));
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 0.0, 240.0, 40.0, 40.0);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap), (LayoutMode::Vertical, 200.0));
|
||||
assert_eq!(l.main_align, MainAlign::Min);
|
||||
assert_eq!((n.child_layout.sizing_h, n.width), (Sizing::Fixed, 40.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_one_rect_pads_ten_and_keeps_it_in_place() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let f = add_layout(&mut s, &[a]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 10.0, [10.0; 4]));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (60.0, 60.0));
|
||||
assert_eq!(canvas(&s, f), (-10.0, -10.0));
|
||||
assert_eq!(canvas(&s, a), (0.0, 0.0));
|
||||
assert_eq!(size(&s, a), (40.0, 40.0));
|
||||
}
|
||||
|
||||
fn filled_frame(s: &mut Session) -> NodeId {
|
||||
id(s.execute("frame.create", &json!({"x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#ff0000"}})).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_frame_mirrors_its_left_and_top_offsets() {
|
||||
let mut s = Session::new();
|
||||
let f = filled_frame(&mut s);
|
||||
rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0);
|
||||
rect_at(&mut s, Some(f), 120.0, 30.0, 40.0, 40.0);
|
||||
let fills = s.doc().unwrap().node(f).unwrap().fills.len();
|
||||
let clip = s.doc().unwrap().node(f).unwrap().clip;
|
||||
add_layout(&mut s, &[f]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Horizontal, 60.0, [30.0, 20.0, 30.0, 20.0]));
|
||||
assert_eq!(l.main_align, MainAlign::Min);
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (180.0, 100.0));
|
||||
assert_eq!((n.fills.len(), n.clip), (fills, clip));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_frame_with_centred_content_spaces_it_between() {
|
||||
let mut s = Session::new();
|
||||
let f = filled_frame(&mut s);
|
||||
rect_at(&mut s, Some(f), 49.0, 49.0, 40.0, 40.0);
|
||||
rect_at(&mut s, Some(f), 211.0, 49.0, 40.0, 40.0);
|
||||
add_layout(&mut s, &[f]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.main_align, l.padding), (MainAlign::SpaceBetween, [49.0; 4]));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (300.0, 138.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_frame_with_stacked_content_fixes_the_content_width() {
|
||||
let mut s = Session::new();
|
||||
let f = filled_frame(&mut s);
|
||||
rect_at(&mut s, Some(f), 20.0, 20.0, 40.0, 40.0);
|
||||
rect_at(&mut s, Some(f), 20.0, 100.0, 40.0, 40.0);
|
||||
add_layout(&mut s, &[f]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap, l.padding), (LayoutMode::Vertical, 40.0, [20.0; 4]));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (80.0, 160.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_group_follows_the_wrap_rule() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
|
||||
let g = id(s.execute("object.group", &json!({"ids": [a, b]})).unwrap());
|
||||
let f = add_layout(&mut s, &[g]);
|
||||
assert_eq!(f, g);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!(l.main_align, MainAlign::SpaceBetween);
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (140.0, 40.0));
|
||||
assert!(n.fills.is_empty() && !n.clip);
|
||||
assert_eq!((canvas(&s, a).0, canvas(&s, b).0), (0.0, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_one_child_group_follows_the_group_rule_not_the_one_child_frame_exception() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let g = id(s.execute("object.group", &json!({"ids": [a]})).unwrap());
|
||||
let r = s.execute("layout.add", &json!({"ids": [g], "direction": "vertical"})).unwrap();
|
||||
assert_eq!(id_of(&r["ids"][0]), Some(g));
|
||||
let n = s.doc().unwrap().node(g).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.padding), (LayoutMode::Vertical, [0.0; 4]));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Fixed, Sizing::Hug));
|
||||
assert!(n.fills.is_empty() && !n.clip);
|
||||
}
|
||||
|
||||
fn add_layout_dir(s: &mut Session, ids: &[NodeId], direction: &str) -> NodeId {
|
||||
let r = s.execute("layout.add", &json!({"ids": ids, "direction": direction})).unwrap();
|
||||
id_of(&r["ids"][0]).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_gap_auto_compares_the_narrower_width_not_the_mean() {
|
||||
// Widths 40 and 100, gap 60: at least the narrower (40), below the mean (70).
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 100.0, 0.0, 100.0, 40.0);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.gap, l.main_align, n.child_layout.sizing_h, n.width), (60.0, MainAlign::SpaceBetween, Sizing::Fixed, 200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_direction_vertical_on_a_horizontal_pair_stacks_with_a_fixed_width_and_no_space_between() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 100.0, 0.0, 40.0, 40.0);
|
||||
let f = add_layout_dir(&mut s, &[a, b], "vertical");
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
// Measured along y the two overlap, so the gap clamps to 0.
|
||||
assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Vertical, 0.0, MainAlign::Min));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v, n.width), (Sizing::Fixed, Sizing::Hug, 140.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_direction_horizontal_on_a_stacked_pair_hugs_the_width() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 0.0, 100.0, 80.0, 60.0);
|
||||
let f = add_layout_dir(&mut s, &[a, b], "horizontal");
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap, l.main_align), (LayoutMode::Horizontal, 0.0, MainAlign::Min));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_overlapping_children_clamp_the_gap_to_zero_and_fractions_round() {
|
||||
let mut s = Session::new();
|
||||
let a = rect_at(&mut s, None, 0.0, 0.0, 40.0, 40.0);
|
||||
let b = rect_at(&mut s, None, 30.0, 0.0, 40.0, 40.0);
|
||||
let f = add_layout(&mut s, &[a, b]);
|
||||
let l = s.doc().unwrap().node(f).unwrap().layout.clone().unwrap();
|
||||
assert_eq!((l.gap, l.main_align), (0.0, MainAlign::Min));
|
||||
// Gaps 5 and 6 average 5.5, which rounds to 6.
|
||||
let mut s = Session::new();
|
||||
let ids: Vec<NodeId> = [0.0, 45.0, 91.0].iter().map(|x| rect_at(&mut s, None, *x, 0.0, 40.0, 40.0)).collect();
|
||||
let f = add_layout(&mut s, &ids);
|
||||
assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().gap, 6.0);
|
||||
// Fractional left and top offsets round to whole padding.
|
||||
let mut s = Session::new();
|
||||
let f = filled_frame(&mut s);
|
||||
rect_at(&mut s, Some(f), 20.4, 30.6, 40.0, 40.0);
|
||||
rect_at(&mut s, Some(f), 120.0, 30.6, 40.0, 40.0);
|
||||
add_layout(&mut s, &[f]);
|
||||
assert_eq!(s.doc().unwrap().node(f).unwrap().layout.clone().unwrap().padding, [31.0, 20.0, 31.0, 20.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shift_a_on_a_frame_with_one_child_keeps_the_inferred_layout() {
|
||||
let mut s = Session::new();
|
||||
let f = filled_frame(&mut s);
|
||||
rect_at(&mut s, Some(f), 20.0, 30.0, 40.0, 40.0);
|
||||
add_layout(&mut s, &[f]);
|
||||
let n = s.doc().unwrap().node(f).unwrap();
|
||||
let l = n.layout.clone().unwrap();
|
||||
assert_eq!((l.mode, l.gap, l.padding, l.main_align), (LayoutMode::Horizontal, 10.0, [30.0, 240.0, 130.0, 20.0], MainAlign::Min));
|
||||
assert_eq!((n.child_layout.sizing_h, n.child_layout.sizing_v), (Sizing::Hug, Sizing::Hug));
|
||||
assert_eq!((n.width, n.height), (300.0, 200.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn align_is_unavailable_for_a_child_in_an_auto_layout_flow() {
|
||||
use crate::cmd::arrange::{align_blocked_by_auto_layout, can_align};
|
||||
|
||||
@@ -76,7 +76,7 @@ fn three(s: &mut Session, mode: &str) -> (NodeId, [NodeId; 3]) {
|
||||
let kids: Vec<NodeId> =
|
||||
(0..3).map(|_| id(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 60, "parent": f})).unwrap())).collect();
|
||||
s.execute("layout.add", &json!({"ids": [f]})).unwrap();
|
||||
s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed"}})).unwrap();
|
||||
s.execute("node.set", &json!({"id": f, "props": {"layoutMode": mode, "gap": 20, "padding": 0, "sizingH": "fixed", "sizingV": "fixed", "width": 300, "height": 300}})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
(f, [kids[0], kids[1], kids[2]])
|
||||
}
|
||||
|
||||
Loaded 100 of 470 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user