Merge main into fix/atomic-temp-name-bytes

This commit is contained in:
dotCooCoo committed 2026-11-28 17:55:30 -08:00
commit 5d363d34aa
6830 files changed
+1092347 -175958

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
# The Workspace gate's additions to .config/cargo-dev.toml (scripts/ci-workspace-tests.sh passes both). The gate runs
# every test of these crates, and their tests spend nearly all their time in sample and pixel loops, which run several
# times faster at opt-level 1; locally they stay at 0, so an edit to them rebuilds fast. craft-pdf (R6 hash and AES-CBC
# loops), craft-pkcs7 and craft-odf (PBKDF2 rounds, monomorphised in the crate) and craft-cms (CLUT builds) run their
# own hot loops in tests, so they take part too.
[profile.dev.package.craft-audio-dsp]
opt-level = 1
[profile.dev.package.craft-audio]
opt-level = 1
[profile.dev.package.craft-media]
opt-level = 1
[profile.dev.package.craft-image-codecs]
opt-level = 1
[profile.dev.package.craft-imaging]
opt-level = 1
[profile.dev.package.craft-pdf]
opt-level = 1
[profile.dev.package.craft-pkcs7]
opt-level = 1
[profile.dev.package.craft-odf]
opt-level = 1
[profile.dev.package.craft-cms]
opt-level = 1
# The runtime under every screen test: each frame of a fixture runs its pass, layout, focus and access tree. At
# opt-level 2 a suite trial runs about 40 percent fewer instructions than at 0 (Table activation 19.8 G to 11.9 G);
# opt-level 1 gives about 30 percent. Every UI crate waits for its compile, which grows by about a minute.
[profile.dev.package.craft-ui-contract]
opt-level = 2
+25
View File
@@ -0,0 +1,25 @@
# The dev-build tuning every craft-libs test build uses: `tools/cl` passes it to each cargo command locally, and
# scripts/ci-workspace-tests.sh passes it (`--config .config/cargo-dev.toml`) to the Workspace gate's builds, so local
# and CI builds are the same. It lives here and not in Cargo.toml's `[profile]` table, which the CI cache key hashes;
# the per-crate levels Cargo.toml sets (craft-video, craft-affinity) still apply.
#
# lto off: with cargo's default, rustc runs thin-local LTO across every optimised crate's codegen units on each rebuild;
# off, a one-line edit re-optimises only the changed units. Dependencies build at opt-level 2, once per target dir and
# cache entry: egui, text shaping, hashing and codecs run in nearly every test.
# craft-theme, craft-behavior and craft-proof run in every screen-test frame or in dictionary-sized tests and are rarely
# edited, so they build at opt-level 1; every other workspace crate stays at 0, where rustc shares generic
# instantiations across crates and an edit to the runtime (craft-ui-contract) rebuilds in seconds.
[profile.dev]
lto = "off"
[profile.dev.package."*"]
opt-level = 2
[profile.dev.package.craft-theme]
opt-level = 1
[profile.dev.package.craft-behavior]
opt-level = 1
[profile.dev.package.craft-proof]
opt-level = 1
+28 -6
View File
@@ -26,11 +26,7 @@ print = { max-threads = 1 }
video-integration = { max-threads = 1 }
[[profile.default.overrides]]
filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))'
test-group = 'gpu'
[[profile.default.overrides]]
filter = 'package(craft-video) & binary(h264_decode)'
filter = 'package(craft-video) & binary(it) & test(/^h264_decode::/)'
test-group = 'video-fixtures'
[[profile.default.overrides]]
@@ -45,7 +41,6 @@ fail-fast = false
slow-timeout = { period = "60s" }
failure-output = "immediate-final"
# Linux and macOS (the resource audit in craft-libs#2058): every GPU consumer shares the one `gpu`
# slot, and the craft-video integration binaries share their fixture directories. Conservative on
# purpose: the in-process mutexes these tests rely on do not reach across nextest's processes.
@@ -59,3 +54,30 @@ test-group = 'gpu'
platform = 'cfg(unix)'
filter = 'package(craft-video) & kind(test)'
test-group = 'video-integration'
# Slowest tests first (priority runs higher values earlier), so the longest ones start at the
# beginning of the run instead of holding the tail. Every test that took over 30 s in the gate's
# run on next (run 44318177438, Linux); the first tier is the one over 60 s.
[[profile.ci.overrides]]
filter = '(package(craft-media) & test(=mxf::tests::hostile::hostile_input_never_panics)) | (package(craft-table) & test(/CellGrid.*::drives$/)) | (package(craft-proto) & test(=imap::gmail_labels_tests::a_mailbox_claimed_huge_cant_fill_memory_with_flags))'
priority = 20
[[profile.ci.overrides]]
filter = '''
(package(craft-design-lint) & test(=mapped_crates_have_no_findings))
| (package(craft-ui-widgets) & test(/SwatchTable.*::activation$/))
| (package(craft-table) & test(/CellGrid.*::activation$/))
| (package(craft-pkcs7) & test(=crypto::new_digital_ids_are_self_signed_and_survive_a_p12_round_trip))
| (package(craft-image-codecs) & test(=tiff_bands::a_blank_fax_page_wider_than_4096_px_passes_the_bomb_guard))
| (package(craft-image-codecs) & test(=codecs::png::streamed_tests::streamed_rows_match_the_whole_image_encoder))
| (package(craft-image-codecs) & test(=codecs::png::parallel_tests::the_parallel_encoder_gives_the_same_bytes_on_any_thread_count))
| (package(craft-image-codecs) & test(=limits::highly_compressible_jpeg_and_gif_still_decode))
| (package(craft-color-ui) & test(=integration::sampling::an_invalid_capture_ends_the_pick_with_a_status))
| (package(craft-docx) & test(=read::chart::tests::hostile_radar_charts_never_panic))
| (package(craft-drawingml) & test(=chart::chartex_tests::large_box_hierarchy_and_stacked_charts_take_linear_work))
| (package(craft-audio) & test(=integration::flac_decode::hostile_input_is_an_error_not_a_panic))
| (package(craft-docx) & test(=comment_save_cost::many_comments_save_without_quadratic_id_searches))
| (package(craft-ui-widgets) & test(/menu::popup::Menu.*::activation$/))
| (package(craft-scraft-format) & test(=b64::tests::size_cap_counts_the_partial_quartet))
'''
priority = 10
+13
View File
@@ -17,3 +17,16 @@ crates/fonts-build/tests/fixture/craft-fonts/fonts/**/OFL.txt -text
# DXF drawing goldens assert exact writer bytes, including LF on every platform.
crates/dxf/tests/data/drawing_*.dxf -text
# The generated components index is compared byte for byte with the generator's LF output (craft-ui test
# components_index): a Windows checkout must not convert its line endings.
docs/components-index.md text eol=lf
# The built-in size files are compared byte for byte with the writer's LF output (craft-theme sizes_tests), and the
# token dumps with the dump writer's (craft-theme dumps test): a Windows checkout must not convert their line endings.
crates/theme/sizes/*.json text eol=lf
crates/theme/tests/dumps/** text eol=lf
# The facade's [features] table is compared with the table the craft features test writes, with LF (craft test
# integration::features): a Windows checkout must not convert its line endings.
crates/craft/Cargo.toml text eol=lf
+13
View File
@@ -33,6 +33,10 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/docs.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/ecproj-format.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -66,6 +70,7 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'dtolnay/rust-toolchain@stable'
'.github/workflows/nightly.yml': []
'.github/workflows/pbr.yml': []
'.github/workflows/pcraft-format.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -81,6 +86,9 @@ workflows:
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/sonarcloud.yml': []
'.github/workflows/theme.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
'.github/workflows/update.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -142,6 +150,11 @@ dependencies:
commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a'
owner_id: 88700172
repo_id: 422287306
'step-security/rust-cache@v2.9.2':
ref: 'v2.9.2'
commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e'
owner_id: 88700172
repo_id: 822636713
'step-security/taiki-e-install-action@v2.87.32':
ref: 'v2.87.32'
commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8'
+12 -3
View File
@@ -52,14 +52,23 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- name: Cache the CC0 sample files
uses: actions/cache@v6.1.0
# Pull requests restore the entry main saved and never write their own: the same
# files saved once per pull request took a share of the 10 GB cache budget.
- name: Restore the CC0 sample files
id: samples
uses: actions/cache/restore@v6.1.0
with:
path: ${{ runner.temp }}/crw-samples
key: crw-samples-${{ hashFiles('crates/crw/tests/samples.json') }}
- name: Fetch the pinned CC0 sample files (raw.pixls.us)
run: python scripts/fetch-crw-samples.py "$RUNNER_TEMP/crw-samples"
- run: cargo test -p craft-crw --release --locked --test samples -- --nocapture
- name: Save the CC0 sample files
if: github.event_name != 'pull_request' && steps.samples.outputs.cache-hit != 'true'
uses: actions/cache/save@v6.1.0
with:
path: ${{ runner.temp }}/crw-samples
key: ${{ steps.samples.outputs.cache-primary-key }}
- run: cargo test -p craft-crw --release --locked --lib -- integration::samples --nocapture
env:
CRAFT_CRW_SAMPLES: ${{ runner.temp }}/crw-samples
CRAFT_CRW_REQUIRE_SAMPLES: "1"
+49
View File
@@ -0,0 +1,49 @@
name: Docs
# Builds the documentation of every workspace crate with warnings as errors, so a public item
# without a doc comment or a broken doc link fails, including crates no other workflow covers.
on:
workflow_dispatch:
push:
branches: [main]
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
pull_request:
paths: ['crates/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docs.yml']
permissions:
contents: read
jobs:
docs:
timeout-minutes: 30
name: Workspace docs
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
with:
# The token isn't needed after checkout; cargo runs build scripts and proc macros from
# dependencies, so don't leave it in .git/config for that third-party code to read.
persist-credentials: false
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: clippy
# Pull requests restore the cache but never save one (a 1.1 GB entry per open PR otherwise).
- uses: step-security/rust-cache@v2.9.2
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
# A lib build selects no dev-dependency, so craft-ui's `testing` stays off as in an app's
# build: warnings that show only without it fail here.
- name: Facade as an app builds it
run: cargo clippy -p craft --lib --locked --features ui,layers,color,draw,imaging -- -D warnings
- name: Docs (links and missing docs)
run: cargo doc --workspace --no-deps --locked --keep-going
env:
RUSTDOCFLAGS: -D warnings
# The crates whose features add public items document with every feature too; the
# per-crate workflows document the media, audio and video crates.
- name: Docs with all features
run: cargo doc -p craft-ui -p craft-ui-contract -p craft-ui-widgets -p craft-ui-panels -p craft-ui-canvas -p craft-ui-patterns -p craft-ui-shell -p craft-doc -p craft-pdf --all-features --no-deps --locked --keep-going
env:
RUSTDOCFLAGS: -D warnings
+10 -1
View File
@@ -15,7 +15,10 @@ on:
- "crates/silhouette-studio/**"
- "crates/tiff/**"
- "crates/heif/**"
- "crates/pst/**"
- "crates/cms/**"
- "crates/cdr/**"
- "crates/texture/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -32,7 +35,10 @@ on:
- "crates/silhouette-studio/**"
- "crates/tiff/**"
- "crates/heif/**"
- "crates/pst/**"
- "crates/cms/**"
- "crates/cdr/**"
- "crates/texture/**"
- "Cargo.toml"
- "Cargo.lock"
- ".github/workflows/formats.yml"
@@ -65,8 +71,11 @@ jobs:
- { crate: craft-svg-paths, features: "" }
- { crate: craft-silhouette-studio, features: "" }
- { crate: craft-tiff, features: "" }
- { crate: craft-heif, features: "testdata" }
- { crate: craft-heif, features: "testdata test-support" }
- { crate: craft-pst, features: "test-writer test-support" }
- { crate: craft-cms, features: "" }
- { crate: craft-cdr, features: "synth" }
- { crate: craft-texture, features: "dds parallel" }
# fmt, clippy with default and with all features, and the tests run in the Workspace gate on
# every OS; this lints each feature alone and checks the web build.
name: ${{ matrix.crate }} feature sets, WASM
+3 -1
View File
@@ -32,7 +32,9 @@ jobs:
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
command: |
python scripts/test-full-validation.py
+7 -9
View File
@@ -3,9 +3,9 @@ name: Keymap
on:
push:
branches: [main]
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
pull_request:
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
paths: ["crates/keymap/**", "crates/settings/**", "crates/ui/**", "crates/ui-contract/**", "crates/ui-widgets/**", "crates/ui-panels/**", "crates/ui-canvas/**", "crates/ui-patterns/**", "crates/ui-shell/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/keymap.yml"]
workflow_dispatch:
permissions:
@@ -46,14 +46,12 @@ jobs:
toolchain: stable
components: clippy
- run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings
# `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU
# to run, so the test steps leave them out.
- run: cargo clippy -p craft-keymap --all-targets --features snapshot --locked -- -D warnings
# Doctests run once, in the `ui` step.
- run: cargo clippy -p craft-keymap --all-targets --features egui --locked -- -D warnings
# Doctests run once, in the `egui` step.
- name: Test core
run: cargo test -p craft-keymap --no-default-features --lib --tests --locked
- name: Test egui dispatch and the shortcuts dialog
run: cargo test -p craft-keymap --features ui --locked
- name: Test egui dispatch
run: cargo test -p craft-keymap --features egui --locked
wasm:
timeout-minutes: 10
name: Keymap WASM
@@ -70,4 +68,4 @@ jobs:
with:
toolchain: stable
targets: wasm32-unknown-unknown
- run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown
- run: cargo check -p craft-keymap --features egui --locked --target wasm32-unknown-unknown
+4
View File
@@ -46,6 +46,10 @@ jobs:
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features ogg -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features serde -- -D warnings
- name: Docs (links and missing docs)
run: cargo doc -p craft-media -p craft-media-testkit --all-features --no-deps --locked
env:
RUSTDOCFLAGS: -D warnings
- run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown
test:
timeout-minutes: 15
+6 -3
View File
@@ -1,7 +1,7 @@
name: Nightly full tests
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
# with CRAFT_HOSTILE_DIVISOR=1 (every member, no sample), and every proptest at its own case count (no PROPTEST_CASES). The
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
on:
schedule:
@@ -26,9 +26,12 @@ jobs:
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
env: CRAFT_PRINT_REQUIRE_QUEUE=0
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=1
setup-command: bash scripts/ci-test-inputs.sh
cache-paths: .test-inputs/photocraft/corpus
cache-key: photocraft-corpus
cache-key-files: scripts/ci-test-inputs.sh
command: cargo nextest run --workspace --all-features --locked --profile ci
# The gate's build (the same targets and profile overrides), with every test at its full count.
command: bash scripts/ci-workspace-tests.sh full
+29
View File
@@ -0,0 +1,29 @@
name: PBR feature tests
on:
workflow_dispatch:
push:
branches: [main, next]
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
pull_request:
paths: ['crates/pbr/**', 'crates/texture/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/pbr.yml']
permissions:
contents: read
jobs:
features:
name: PBR ${{ matrix.mode }} tests
strategy:
fail-fast: false
matrix:
include:
- { mode: serial, arguments: '' }
- { mode: parallel, arguments: '--features parallel' }
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["ubuntu-latest"]'
craft-fonts-ref: ''
require-craft-fonts: false
timeout-minutes: 30
command: cargo test -p craft-pbr --locked ${{ matrix.arguments }}
+1 -1
View File
@@ -48,7 +48,7 @@ jobs:
python scripts/test-fetch-pdf-test-fonts.py
python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts"
echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV"
- run: cargo test -p craft-pdf --all-features --locked --test unicode_writing --test upstream_compatibility --test upstream_reading
- run: cargo test -p craft-pdf --all-features --locked --lib -- integration::unicode_writing integration::upstream_compatibility
- run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked
backends:
name: PDF vendored contracts
+43
View File
@@ -0,0 +1,43 @@
name: Suite themes
on:
workflow_dispatch:
push:
branches: [main]
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
pull_request:
paths: ['crates/theme/**', 'crates/theme-store/**', 'crates/atomic/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/theme.yml']
permissions:
contents: read
jobs:
theme:
timeout-minutes: 15
name: Theme lint, tests, WASM
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
with:
# The token isn't needed after checkout; cargo runs build scripts and proc macros from
# dependencies, so don't leave it in .git/config for that third-party code to read.
persist-credentials: false
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt -p craft-theme --check
- run: cargo clippy -p craft-theme --all-targets --all-features --locked -- -D warnings
- run: cargo clippy -p craft-theme --all-targets --locked -- -D warnings
- run: cargo test -p craft-theme --all-features --locked
- run: cargo check -p craft-theme --all-features --locked --target wasm32-unknown-unknown
- run: cargo check -p craft-ui --lib --locked
- run: cargo fmt -p craft-theme-store --check
- run: cargo clippy -p craft-theme-store --all-targets --all-features --locked -- -D warnings
- name: Docs (links and missing docs)
run: cargo doc -p craft-theme -p craft-theme-store --all-features --no-deps --locked
env:
RUSTDOCFLAGS: -D warnings
- run: cargo test -p craft-theme-store --all-features --locked
- run: cargo check -p craft-theme-store --all-features --locked --target wasm32-unknown-unknown
+4 -4
View File
@@ -18,10 +18,10 @@ concurrency:
cancel-in-progress: true
# fmt, clippy and the tests with default and with all features run in the Workspace gate on every
# OS; this runs the egui feature alone.
# OS; this runs the ui feature alone.
jobs:
update:
name: Update with egui alone
name: Update with ui alone
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
@@ -38,5 +38,5 @@ jobs:
with:
toolchain: stable
components: clippy
- run: cargo clippy -p craft-update --all-targets --locked --features egui -- -D warnings
- run: cargo test -p craft-update --locked --features egui -- --nocapture
- run: cargo clippy -p craft-update --all-targets --locked --features ui -- -D warnings
- run: cargo test -p craft-update --locked --features ui -- --nocapture
+5 -7
View File
@@ -17,11 +17,11 @@ concurrency:
group: window-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests with default and with all features (egui and restore together) run in
# the Workspace gate on every OS; this runs each feature alone.
# fmt, clippy and the tests with default and with all features run in the Workspace gate on every
# OS; this runs the ui feature alone.
jobs:
window:
name: Window with each feature alone
name: Window with ui alone
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
@@ -38,7 +38,5 @@ jobs:
with:
toolchain: stable
components: clippy
- run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings
- run: cargo test -p craft-window --locked --features egui -- --nocapture
- run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings
- run: cargo test -p craft-window --locked --features restore -- --nocapture
- run: cargo clippy -p craft-window --all-targets --locked --features ui -- -D warnings
- run: cargo test -p craft-window --locked --features ui -- --nocapture
+74 -38
View File
@@ -16,19 +16,19 @@ permissions:
contents: read
concurrency:
# A pull request, and main, each have one group, so a newer push cancels the run it supersedes;
# the newest push's run still tests everything before it. Every other run (a release tag, a
# manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced
# while queued: a release run always finishes, and the scheduled run saves the caches.
# A pull request and main each have one group, so a newer push cancels the run it supersedes; the
# newest push's run still tests everything before it. Every other run (a release tag, a manual
# run, the scheduled run) gets a group of its own and is neither cancelled nor replaced while
# queued: a release run always finishes, and the scheduled run saves the caches.
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }}
jobs:
# Whether this run needs the macOS and Windows legs, and which tests every leg runs
# (craft-common-actions' select-platforms). On a pull request the macOS and Windows legs run only
# when it can change platform behaviour: a crate with platform cfg code or one that depends on
# it, the build setup, or a file outside the crates. The tests are those of the crates a change
# reaches: the crates that own a changed file, the crates whose Cargo.toml declares a read of it
# (craft-common-actions' select-platforms). A pull request runs the Linux legs only, unless it
# has the full-ci label (see native-platforms); every other event runs the macOS and Windows legs
# too. The tests are those of the crates a change reaches: the crates that own a changed file,
# the crates whose Cargo.toml declares a read of it
# (`[package.metadata.craft] reads`, which this job checks is complete), and every crate that
# depends on those. The build setup, a crate's own Cargo.toml or a file outside the crates other
# than documentation runs every test; documentation alone runs none. The full-ci label runs
@@ -41,6 +41,9 @@ jobs:
platform: ${{ steps.select.outputs.platform }}
tests: ${{ steps.select.outputs.tests }}
filter: ${{ steps.select.outputs.filter }}
audit: ${{ steps.audit.outputs.audit }}
profile: ${{ steps.audit.outputs.profile }}
deps-profile: ${{ steps.audit.outputs.deps-profile }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -59,6 +62,43 @@ jobs:
select-os: '["windows-latest","macos-latest"]'
select-tests: true
label: full-ci
# Whether the selection reaches a replay-audit crate, which runs the Linux leg as a build job
# and three test shards (see `native`), and the hash of the profile overrides every test build
# passes (scripts/ci-workspace-tests.sh), which names the Workspace legs' cache entries:
# rust-cache's key does not hash these files, and an entry built with other overrides would be
# rebuilt in full on every run. Other events than a pull request check out only these files.
# The macOS and Windows legs cache dependencies only, so `deps-profile` hashes only the
# settings that reach a dependency: `[profile.dev]` and `[profile.dev.package."*"]`. Every
# other override names a workspace crate (scripts/test-workspace-tests.py), so changing one
# keeps those entries.
- uses: actions/checkout@v7.0.1
if: github.event_name != 'pull_request'
with:
persist-credentials: false
sparse-checkout: |
scripts/ci-workspace-tests.sh
.config/cargo-*.toml
sparse-checkout-cone-mode: false
- id: audit
env:
CRAFT_TESTS: ${{ steps.select.outputs.tests }}
CRAFT_TEST_FILTER: ${{ steps.select.outputs.filter }}
CRAFT_TEST_SKIP: ${{ steps.select.outputs.skip }}
run: |
echo "audit=$(bash scripts/ci-workspace-tests.sh audit)" >> "$GITHUB_OUTPUT"
echo "profile=$(cat .config/cargo-dev.toml .config/cargo-ci.toml | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT"
# An assignment, so a failure stops the step (`bash -e`) instead of naming every entry `v2-`.
deps=$(python3 -I - <<'PY'
import hashlib, json, tomllib
kept = []
for path in (".config/cargo-dev.toml", ".config/cargo-ci.toml"):
with open(path, "rb") as file:
dev = tomllib.load(file)["profile"]["dev"]
kept.append([dev, dev.pop("package", {}).get("*", {})])
print(hashlib.sha256(json.dumps(kept, sort_keys=True).encode()).hexdigest()[:12])
PY
)
echo "deps-profile=$deps" >> "$GITHUB_OUTPUT"
# The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each
# main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo
@@ -74,8 +114,15 @@ jobs:
with:
os: '["ubuntu-latest"]'
cache-workspace-crates: true
cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}
cold-build: ${{ github.event.schedule == '17 0 * * *' }}
lint-cache: false
# The vendored crates are on the workspace `exclude` list and craft-pdf's read-only contract is a
# workspace of its own (pdf.yml tests it), so unreached-rs has no module tree for them.
unreached-rs-allow: |
**/fixtures/**
vendor/**
crates/pdf/read-only-contract/**
timeout-minutes: &timeout 120
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
tools: &tools cargo-nextest@0.9.150
@@ -115,34 +162,33 @@ jobs:
fi
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
command: &command |
# The tests run once, with every feature, in parallel across test binaries; nextest skips
# doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose
# tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's
# first clippy run; the last command runs the crates whose tests check behaviour with a
# feature off, which an all-features build cannot reach.
# Every build is the whole workspace's, as on main; the filter narrows only the run. The
# doctests run for the whole workspace: `cargo test -p <selected>` would resolve features
# over the selected crates only and rebuild the dependencies whose features differ.
if [ "$CRAFT_TESTS" = none ]; then
echo "No crate changed: no tests to run."
exit 0
fi
cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests
cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests
# A selection that reaches a replay-audit crate builds once in a `build` job, which writes
# three nextest archives and then runs the doctests; three shard legs run them in parallel:
# every selected test outside the replay audit's crates and craft-draw, those crates (run plainly,
# then the audit crates with the audit), and craft-image-codecs with default features. Any other selection
# (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh
# holds every step.
test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }}
shard-archives: ${{ needs.platforms.outputs.audit == 'true' }}
archive-command: ${{ needs.platforms.outputs.audit == 'true' && 'bash scripts/ci-workspace-tests.sh archive' || '' }}
after-archive-command: bash scripts/ci-workspace-tests.sh doctest
shard-command: bash scripts/ci-workspace-tests.sh shard
command: &command bash scripts/ci-workspace-tests.sh run
# The macOS and Windows legs, when `platforms` says this run needs them, with the Linux leg's
# inputs.
# The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux
# leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on
# every push to main and on main's scheduled runs.
# A pull request that needs them before it merges gets the full-ci label.
native-platforms:
name: Workspace
needs: platforms
if: needs.platforms.outputs.platform == 'true'
if: needs.platforms.outputs.platform == 'true' && (github.event_name != 'pull_request' || contains(github.event.pull_request.labels.*.name, 'full-ci'))
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest","macos-latest"]'
lint-cache: false
# Named by the dependency settings alone (`deps-profile`).
cache-version: v2-${{ needs.platforms.outputs.deps-profile }}
timeout-minutes: *timeout
tools: *tools
craft-fonts-ref: *craft-fonts
@@ -160,16 +206,6 @@ jobs:
cache-key-files: *cache-key-files
lint-command: *lint
command: *command
windows-command: |
if [ "$CRAFT_TESTS" = none ]; then
echo "No crate changed: no tests to run."
exit 0
fi
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests
cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench
cargo test --workspace --doc --all-features --locked
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests
# Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), and
# every run restores only the newest. This deletes the older ones as soon as the Linux leg is
+1
View File
@@ -9,3 +9,4 @@ target/
/.claude/
.idea/
/vendor/*/target
__pycache__/
+2 -2
View File
@@ -65,7 +65,7 @@ The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119
Shared Rust libraries for the Craft Apps: a Cargo workspace (edition 2024, resolver 3) of crates under `crates/<name>`. See `README.md` for layout and released versions.
- **New crates** go in `crates/<name>`, named `craft-<name>`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true`.
- **New crates** go in `crates/<name>`, named `craft-<name>`, inherit the workspace package fields and lints, and are listed in `[workspace.dependencies]`. A new crate's `Cargo.toml` includes `[lints] workspace = true` (`crates/font-os-windows` is the one exception; see `unsafe` below).
- **No app code.** A crate here is useful to more than one app and does not depend on any app.
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, and no crate in `crates/` allows it, so no module here may use `unsafe`. The one exception is vendored upstream code in `vendor/hayro-syntax`.
- **`unsafe`:** the workspace sets `unsafe_code = "forbid"`, so no module here may use `unsafe`, with two exceptions: vendored upstream code in `vendor/hayro-syntax`, and `crates/font-os-windows`, because loading a font into the running Windows session needs `AddFontResourceW`, which the Windows crates offer only as an unsafe call. That crate copies the workspace lints with `unsafe_code = "deny"` instead of `[lints] workspace = true`, and allows `unsafe` only on the functions that make Win32 calls.
- **Checks for the crates you changed:** `cargo fmt --check`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo test -p <crate>`.
+35 -6
View File
@@ -12,29 +12,35 @@ author, source and license. Library code and original assets are under the repos
| `crates/cms/profiles/photocraft-coated-cmyk.icc` | PhotoCraft contributors; generated by `craft_cms::synth::coated_cmyk` | [PhotoCraft `crates/cms`](https://github.com/storytold/photocraft/tree/b3222ee8e7e6bcb4799c37f904c595f20f9baf5e/crates/cms) | CC0-1.0 |
| `crates/cms/profiles/craft-coated-fogra39.icc` | craft-libs contributors; generated by `crates/cms/tests/fogra39.rs` from the FOGRA39 data below | this repository | CC0-1.0 |
| `crates/ppt-binary/tests/fixtures/old-talk.pps` | DeckCraft contributors; a one-slide PowerPoint 97-2003 show built from records by `crates/ppt-binary/src/tests.rs` (`the_pps_fixture_is_a_built_presentation`, with `CRAFT_WRITE_PPT_FIXTURE=1`); no PowerPoint involved | [storytold/deckcraft#1137](https://github.com/storytold/deckcraft/pull/1137) | CC0-1.0 |
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@5a9a7f8](https://github.com/aiongg/craft-font-index/tree/5a9a7f8038c8f3e2e1583a79c92a816e8e71b34f) | Apache-2.0 |
| `crates/font-store/index/sources.json` (unmodified) | craft-font-index contributors | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
| `crates/font-store/index/indexes/google-fonts.json.gz` (unmodified) | craft-font-index contributors; generated from the METADATA.pb files of [google/fonts](https://github.com/google/fonts) at `45e3d5269e4a17d823f6d84470bc084dc5ae46f6` | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
| `crates/font-store/index/indexes/noto.json.gz` (unmodified) | craft-font-index contributors; generated from [notofonts/notofonts.github.io](https://github.com/notofonts/notofonts.github.io) at `93fac8abebe6c7fed0c5b7d2456d8fa484fa146c` and [noto-cjk](https://github.com/notofonts/noto-cjk) releases | [aiongg/craft-font-index@995ef20](https://github.com/aiongg/craft-font-index/tree/995ef2000a0159d70da245e22cfa0797a0756ae8) | Apache-2.0 |
| `crates/font-manager/tests/data/preview-vectors.json` (sample sentences) | Google Fonts `lang/` contributors; texts from the Universal Declaration of Human Rights via Eric Muller's UDHR in Unicode (translations' own terms not checked); the Iroha poem is public domain | [google/fonts `lang/`](https://github.com/google/fonts/tree/45e3d5269e4a17d823f6d84470bc084dc5ae46f6/lang) at `45e3d52` | Apache-2.0 |
| `crates/cms/tests/data/FOGRA39.txt` (unmodified) | Fogra | [Fogra characterisation data](https://fogra.org/en/downloads/work-tools/characterisation-data), `FOGRA39_to_FOGRA60_v2.zip` | Fogra terms: free use and redistribution, unmodified, with Fogra identified as the source; "FOGRA39" identifies the reference data only and implies no certification, approval or endorsement by Fogra (full text in [NOTICE](NOTICE)) |
| `vendor/linesweeper/tests/regression/`, `vendor/linesweeper/proptest-regressions/`, the `.snap` files under `vendor/linesweeper/src/` and the path data in `vendor/linesweeper/benches/painted_dreams.rs` (all unmodified; hashes in `vendor/linesweeper/SOURCE.json`) | As published in the package, whose manifest names Joe Neeman as author and records no other source | [linesweeper 0.5.0](https://crates.io/crates/linesweeper/0.5.0) | MIT OR Apache-2.0 (the package's `license` field) |
| `crates/i18n/data/collation.postcard` | Unicode, Inc. (ICU 78.1 collation data, CLDR 48.2.1); generated by `crates/i18n/data/generate-collation.sh` | [ICU](https://github.com/unicode-org/icu/releases/tag/release-78.1rc) | Unicode-3.0 |
| `crates/i18n/data/numbers.postcard` | Unicode, Inc. (CLDR 48.2.1 decimal symbols, digits and plural rules); generated by `crates/i18n/data/generate.sh` with `icu4x-datagen` 2.3.0 | [CLDR 48.2.1](https://cldr.unicode.org/) | Unicode-3.0 |
| `crates/i18n/data/dates.postcard` | Unicode, Inc. (CLDR 48.2.1 Gregorian date and time patterns, month and weekday names, week data); generated by `crates/i18n/data/generate.sh` with `icu4x-datagen` 2.3.0 | [CLDR 48.2.1](https://cldr.unicode.org/) | Unicode-3.0 |
| `crates/text/assets/hyphen/en-us.dic` | Grady Ward (Moby Hyphenator II), converted by DesignCraft | [Project Gutenberg eBook #3204](https://www.gutenberg.org/ebooks/3204) | Public domain |
| `crates/proof/data/en-words.dic` | Grady Ward (Moby Hyphenator II word list); break points dropped by craft-proof contributors with `crates/proof/examples/en_words.rs` | [Project Gutenberg eBook #3204](https://www.gutenberg.org/ebooks/3204), via craft-i18n `language-data/en-us/en-us.dic` | Public domain |
| `crates/proof/data/en-extra.txt` | WordCraft contributors (original list, no other dictionary copied) | craft-i18n `language-data/en-us/en-extra.txt` | MIT OR Apache-2.0 |
| `crates/text/assets/hyphen/en-us.pat` | DesignCraft contributors, trained from the Moby Hyphenator II list | `crates/text/examples/hyphgen.rs` | CC0-1.0 |
| Patterns embedded through `hypher` (optional `craft-text` language features) | hyph-utf8 authors, per language | [tex-hyphen](https://github.com/hyphenation/tex-hyphen), as packaged in [hypher](https://github.com/typst/hypher/tree/main/patterns) | Per file header: LPPL, MIT, BSD-3-Clause, Unlicense or a permit-any-use notice (or a choice including one); Slovak (`hyph-sk.tex`, embedded whenever `hypher/slovak` is on: feature `slovak-gpl`, or another dependency through feature unification) is GPL-2.0-or-later; Spanish (`hyph-es.tex` 5.0, Javier Bezos, CervanTeX) is MIT |
| Word-break dictionaries and LSTM models embedded through `icu_segmenter_data` (optional `craft-text` features `thai`, `lao`, `khmer`, `burmese`) | Unicode, Inc. and ICU4X contributors | [ICU4X](https://github.com/unicode-org/icu4x) | Unicode-3.0 |
| MikkTSpace tangent generation compiled in through `mikktspace` (`craft-mesh-ops`) | Benjamin Wasty, David Harvey-Macaulay and Layl Bongers; translated from the C original by Morten S. Mikkelsen | [mikktspace 0.3.0](https://crates.io/crates/mikktspace/0.3.0), [gltf-rs/mikktspace](https://github.com/gltf-rs/mikktspace) | MIT OR Apache-2.0 (the package's `license` field); its `src/generated.rs` also carries the C original's 2011 notice, reproduced in [`crates/mesh-ops/ATTRIBUTION.md`](crates/mesh-ops/ATTRIBUTION.md) |
| `crates/ui/tests/fonts/NotoSansArabic-test.ttf` (subset to the test strings, default weight set to 100, width axis dropped) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
| `crates/ui/tests/fonts/NotoSansCJKsc-test.otf` (subset to the test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
| `crates/ui/tests/fonts/NotoSansArabic-screens.ttf` (instance at weight 400 and width 100, subset to the screen test strings) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
| `crates/ui/tests/fonts/NotoSansCJKsc-screens.otf` (subset to printable ASCII and the screen test strings) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansCJK.txt`) |
| `crates/ui/tests/fonts/NotoSansThai-screens.ttf` (instance at weight 400 and width 100, subset to the screen test strings) | The Noto Project Authors | [google/fonts@8b0a1d0 `ofl/notosansthai`](https://github.com/google/fonts/tree/8b0a1d0f5983c89bc2b93f1b5fb55f9e252744b5/ofl/notosansthai), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansThai.txt`) |
| `crates/imaging/tests/fonts/NotoSansArabic-digits.ttf` (instance at weight 400 and width 100, subset to the Arabic-Indic digits and separators U+0660–U+066C) | The Noto Project Authors | [google/fonts@7085eb8 `ofl/notosansarabic`](https://github.com/google/fonts/tree/7085eb89a950e85db5b166b7a58d414544b4140c/ofl/notosansarabic), via craft-fonts | OFL-1.1 (`licenses/ui-test-fonts/OFL-NotoSansArabic.txt`) |
| `crates/crw/tests/samples.json` (manifest only; the 11 raw files are not bundled, `scripts/fetch-crw-samples.py` downloads them outside the checkout) | The photographers who contributed each file to raw.pixls.us (Canon EOS D30, D60, 10D ×3, 300D ×2, Digital Rebel, PowerShot G1, G5, G6) | [raw.pixls.us](https://raw.pixls.us/), each file's `getfile.php` URL and SHA-256 in the manifest | CC0-1.0 (as published by raw.pixls.us for each file) |
| `crates/crw/src/tables.rs`, `crates/crw/clean-room/logs/table_sel*.json` | craft-crw contributors (derived in LightCraft, 2026-10, by known-plaintext alignment of the sample files' entropy streams; `crates/crw/clean-room/02-crw-format.md`) | this repository | MIT OR Apache-2.0 |
| `crates/crw/clean-room/logs/private-corpus.tsv` (file names, sizes and SHA-256 of the maintainer's own EOS D60 files; no image content) | craft-crw contributors (LightCraft derivation record) | this repository | MIT OR Apache-2.0 |
| `crates/prc/src/acof/table.rs` (the rows of the PRC `Double` prefix-code table, reformatted as Rust tuples) | Kristof Ralovich (prc-rs); the table is defined by ISO 14739-1 | [ralovich/prc-rs@287b671](https://github.com/ralovich/prc-rs/blob/287b671bb5b31b05efb5ec1b98f7c359b9e4dd7d/src/double.rs), through [PdfCraft `crates/prc`](https://github.com/storytold/pdfcraft/tree/80e26e674d1aa33078e83c8139875047f3289eb6/crates/prc) | MIT (`licenses/prc-rs/LICENSE.txt`; the notice is also in the file header) |
| `crates/math/tests/corpus/equations.tsv`, `crates/math/tests/corpus/latex.tsv` (unmodified) | shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/` | MIT OR Apache-2.0 |
| `crates/math/tests/corpus/omml/*.xml` (unmodified) | WordCraft and DeckCraft contributors, collected by shuff57 (equaSHion) | [storytold/craft-libs#29](https://github.com/storytold/craft-libs/pull/29) at `7a6ef6b9`, `corpus/omml/` | MIT OR Apache-2.0 |
| `crates/font-subset/tests/data/{abeezee,abel,bbhbartle,librefranklin,orbitron,sarabun}/` (unmodified; each with its `OFL.txt`) | The ABeeZee, Abel, BBH, Libre Franklin, Orbitron and Sarabun Project Authors | [google/fonts@e7db6ca `ofl/`](https://github.com/google/fonts/tree/e7db6ca/ofl) | OFL-1.1 |
| `crates/font-subset/tests/data/ubuntu/Ubuntu-Regular.ttf` (unmodified; with `LICENCE.txt`) | Canonical Ltd. (Dalton Maag) | [google/fonts@e7db6ca `ufl/ubuntu`](https://github.com/google/fonts/tree/e7db6ca/ufl/ubuntu) | Ubuntu-font-1.0 |
| `crates/font-subset/tests/data/notosanscjk/NotoSansCJKsc-test.otf` (subset to the test strings; with `OFL.txt`) | The Noto Project Authors (Adobe, Google) | [notofonts/noto-cjk@f8d1575 `Sans/OTF/SimplifiedChinese`](https://github.com/notofonts/noto-cjk/tree/f8d157532fbfaeda587e826d4cd5b21a49186f7c/Sans/OTF/SimplifiedChinese), via storytold/font-preview-service | OFL-1.1 |
| `crates/ui-contract/fonts/inter/Inter-Regular.ttf`, `crates/ui-contract/fonts/inter/Inter-SemiBold.ttf` (subset to 1,298 Latin, Greek, and Cyrillic codepoints with `fontTools` 4.62.1: `hinting=True`, `notdef_outline=True`, `layout_features=["*"]`, `name_IDs=["*"]`, `glyph_names=False`) | The Inter Project Authors | `storytold/craft-fonts` (`fonts/inter/Inter-Regular.ttf` sha256 `40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82`, `fonts/inter/Inter-SemiBold.ttf` sha256 `78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3`, Inter 4.001 `git-9221beed3`) | OFL-1.1 (`crates/ui-contract/fonts/inter/OFL.txt`) |
Original assets are covered by the repository licence.
@@ -90,6 +96,7 @@ and the exact transfer revision are recorded in each vendored crate's SOURCE.jso
| `crates/raster-codecs/src/xpm/x11_colors.rs` | X.Org Foundation and X11 contributors (X11 `rgb.txt` colour names and values, normalised into a lookup table) | <https://cgit.freedesktop.org/xorg/app/rgb/tree/rgb.txt>, via [PhotoCraft `crates/codecs`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/codecs/src/codecs/xpm) | MIT (X.Org app/rgb) |
| `crates/psd/tests/fixtures/atn/*.atn` (seven synthetic action sets, encoded field by field; `crates/psd/tests/fixtures/atn/README.md`) | PhotoCraft contributors | [PhotoCraft `crates/psd/tests/fixtures/atn`](https://github.com/storytold/photocraft/tree/63b641b55e54bf8f5c83efd977fdb16a2c255431/crates/psd/tests/fixtures/atn) | MIT OR Apache-2.0 |
| `crates/lottie/tests/fixtures/` | EffectCraft contributors (original work: four hand-written Lottie JSON documents, written from the public Lottie format description; not exported from any Adobe product or third-party file) | [EffectCraft `crates/lottie/tests/fixtures`](https://github.com/storytold/effectcraft/tree/e18f48fb/crates/lottie/tests/fixtures) | MIT OR Apache-2.0 |
| `crates/i18n-build/tests/fixture/` | craft-libs contributors (original work: nine hand-written catalogs of a few common interface words, in craft-i18n's catalog format; not copied from craft-i18n or any app) | this repository | MIT OR Apache-2.0 |
| `crates/pkcs7/tests/data/` | PdfCraft contributors (original work: throw-away test keys and certificates made with OpenSSL 3 for these tests, as seven PKCS #12 files with the password `test` and two PEM certificates; they protect nothing; commands in `crates/pkcs7/tests/data/README.md`) | [PdfCraft `crates/sign/tests/data`](https://github.com/storytold/pdfcraft/tree/1d7a9f9f/crates/sign/tests/data) | MIT OR Apache-2.0 |
| `crates/affinity/tests/support/corpus.tsv`, `crates/affinity/tests/support/affinity3-signatures.txt` (manifest and measured signatures only; the 113 files, 90 of them documents, are not bundled, `scripts/fetch-affinity-corpus.sh` downloads them outside the checkout) | The authors of each document: samuel-etver (vector-art), satoshoe-dev (affinity-samples), Seth A. Robinson (Patchy fixtures), Nick Beeuwsaert (AFDesignLoad), Jeremy Cantu (Branding), eviltwo (AssetStoreTemplate), Square (leakcanary) | each file's pinned upstream URL and SHA-256 in the manifest; every name from [VectorCraft `xtask/src/affinity_corpus.rs`](https://github.com/storytold/vectorcraft/blob/bada8e17103db9917de44e40a1cead5a7fc71c3c/xtask/src/affinity_corpus.rs) and [PhotoCraft `xtask/affinity-corpus.sha256`](https://github.com/storytold/photocraft/blob/629751503165118d5fec5f70e64fe2d6592f7b53/xtask/affinity-corpus.sha256) | CC0-1.0, MIT or Apache-2.0 (per file, in the manifest) |
| `crates/raw/docs/coverage/adobe-cameras.tsv` | Facts (maker, model, extension, profile, minimum Camera Raw version) parsed by LightCraft contributors from Adobe's published list | [Adobe Camera Raw supported cameras](https://helpx.adobe.com/camera-raw/desktop/dng-and-file-formats/camera-raw-plug-supported-cameras.html), Wayback capture 20261003133011; moved from [LightCraft `docs/raw`](https://github.com/storytold/lightcraft/tree/5ff567a4a2e067bef1b6bce152c11e7f727ccbaf/docs/raw) | Facts, not copyrightable expression; the file is MIT OR Apache-2.0 |
@@ -120,6 +127,8 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
`crates/audio-dsp` combines FilmCraft `crates/audio-dsp` at `3f137a7ed420cac79b32145f5243b7f98b31f71c` and SoundCraft `crates/dsp` at `648ed9db9a0e98cc55643babffac381521a556c8` (both MIT OR Apache-2.0). `crates/audio-dsp/NOTICE` keeps the copyright notices of both projects.
`crates/audio-dsp/src/effects/voice.rs` adapts the two crossfaded read taps of SoundCraft `crates/dsp/src/plugins/pitch.rs` and the YIN pitch tracker of `crates/dsp/src/pitch_detect.rs` at `915481be1b49d7e0502e07b059d0c0198c61911a` (MIT OR Apache-2.0). The taps are centered on a fixed 10 ms latency and spaced by whole periods of the tracked pitch, and the tracker runs on a decimated copy of the input in buffers sized at creation.
## GIMP palette reader
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
@@ -167,6 +176,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
## GPU device selection
`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both.
## Dalvik DEX inspection
`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained.
@@ -180,3 +193,19 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
`crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository.
Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor.
## Y4M range-backed playback
`crates/media-source/src/y4m.rs` adapts the in-house [FilmCraft Y4mSource at 3f137a7e](https://github.com/storytold/filmcraft/blob/3f137a7ed420cac79b32145f5243b7f98b31f71c/crates/codecs/src/y4m.rs), MIT OR Apache-2.0. Original playback by Lloyd Nicholson ([FilmCraft #1303](https://github.com/storytold/filmcraft/pull/1303)); shared-parser integration by Dylan M. Taylor ([FilmCraft #4862](https://github.com/storytold/filmcraft/pull/4862)). The adaptation changes source/frame types and declines payloads above the shared media allocation ceiling before playback. The parser and its previous header-safety work remain in `craft-y4m` ([craft-libs #933](https://github.com/storytold/craft-libs/pull/933)).
`crates/media-source/tests/it/y4m.rs` contains original repository-authored synthetic test data under MIT OR Apache-2.0: literal YUV samples and a sparse reader that reports only the length of an oversized frame. It does not use external media or decoder output.
## Material graph runtime
`crates/material-graph` moves the graph text format, parser, evaluator, pixel-program compiler, and tests from
[TextureCraft's SPP importer at 22a37c29](https://github.com/vangel76/texturecraft/tree/22a37c29e98d8e6fc8c5e611e22f0ab95b83243d/crates/graph)
(MIT OR Apache-2.0). [xilefenko introduced this runtime in TextureCraft](https://github.com/vangel76/texturecraft/commit/af862722be61bd7050ac782ec57a5e8938a5b017),
adapting code from [PiJellyPin's MaterialCraft](https://github.com/PiJellyPin/MaterialCraft). See the crate's
`NOTICE` for the original attribution. This extraction retains vangel76's subsequent evaluator and GPU work.
The format reference and tests are from the same TextureCraft source. The tests' numerical rule tables document
their provenance in their headers.
Generated
+2213 -411
View File
File diff suppressed because it is too large. Load diff
+71 -15
View File
@@ -1,7 +1,7 @@
[workspace]
resolver = "3"
members = ["crates/*"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu"]
exclude = ["vendor/krilla", "vendor/hayro", "vendor/hayro-interpret", "vendor/hayro-syntax", "vendor/hayro-jbig2", "vendor/hayro-cmap", "vendor/hayro-postscript", "vendor/linesweeper", "vendor/vello_common", "vendor/vello_cpu", "vendor/kurbo"]
[workspace.package]
version = "0.1.0"
@@ -11,6 +11,7 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-android-res = { path = "crates/android-res" }
craft-audio-dsp = { path = "crates/audio-dsp" }
craft-xfa = { path = "crates/xfa" }
craft-evm = { path = "crates/evm" }
@@ -31,14 +32,22 @@ craft-ssip = { path = "crates/ssip" }
craft-ber = { path = "crates/ber" }
craft-proto = { path = "crates/proto" }
craft-render-parity = { path = "crates/render-parity" }
craft-shared-vec = { path = "crates/shared-vec" }
acadrust = "=0.6.6"
log = "0.4"
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
craft-plist = { path = "crates/plist" }
craft-gpu-device = { path = "crates/gpu-device" }
craft-wasm = { path = "crates/wasm" }
craft-gpu-yuv = { path = "crates/gpu-yuv" }
craft-platform = { path = "crates/platform" }
craft-png = { path = "crates/png" }
craft-aep = { path = "crates/aep" }
craft-affinity = { path = "crates/affinity" }
craft-win32 = { path = "crates/win32" }
craft-appkit = { path = "crates/appkit" }
craft-wayland = { path = "crates/wayland" }
craft-cdr = { path = "crates/cdr" }
craft-ai = { path = "crates/ai" }
craft-ai-core = { path = "crates/ai-core" }
craft-anicraft-format = { path = "crates/anicraft-format" }
@@ -61,6 +70,7 @@ thiserror = "2"
craft-gzip = { path = "crates/gzip" }
craft-gridcraft-format = { path = "crates/gridcraft-format" }
craft-aaf = { path = "crates/aaf" }
craft-behavior = { path = "crates/behavior" }
craft-atomic = { path = "crates/atomic" }
# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/app/ai-agents).
craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "d94a3593adcff504eaaad9e5aee4c84fd2f07a72" }
@@ -72,13 +82,20 @@ craft-codepage = { path = "crates/codepage" }
craft-cms = { path = "crates/cms" }
craft-cloud = { path = "crates/cloud" }
craft-cloud-local = { path = "crates/cloud-local" }
craft-cloud-ui = { path = "crates/cloud-ui" }
craft-color = { path = "crates/color" }
craft-scopes = { path = "crates/scopes" }
craft-color-ui = { path = "crates/color-ui" }
craft-color-transform = { path = "crates/color-transform" }
craft-frame = { path = "crates/frame" }
craft-crs = { path = "crates/crs" }
craft-crw = { path = "crates/crw" }
craft-csv = { path = "crates/csv" }
craft-dav = { path = "crates/dav" }
craft-automation = { path = "crates/automation" }
craft-browse = { path = "crates/browse" }
craft = { path = "crates/craft" }
craft-design-lint = { path = "crates/design-lint" }
craft-dialogs = { path = "crates/dialogs" }
craft-doc-binary = { path = "crates/doc-binary" }
craft-docx = { path = "crates/docx" }
@@ -89,6 +106,7 @@ craft-deckcraft-format = { path = "crates/deckcraft-format" }
craft-designcraft-format = { path = "crates/designcraft-format" }
craft-dxf = { path = "crates/dxf" }
craft-drawingml = { path = "crates/drawingml" }
craft-ease = { path = "crates/ease" }
craft-eps = { path = "crates/eps" }
craft-elf = { path = "crates/elf" }
craft-file-formats = { path = "crates/file-formats" }
@@ -100,6 +118,7 @@ vectorcraft-pathops = { git = "https://github.com/storytold/vectorcraft.git", re
craft-doc = { path = "crates/doc" }
craft-docpath = { path = "crates/docpath" }
craft-dpx = { path = "crates/dpx" }
craft-draw = { path = "crates/draw" }
craft-dwg = { path = "crates/dwg" }
craft-fcproj-format = { path = "crates/fcproj-format" }
craft-ecproj-format = { path = "crates/ecproj-format" }
@@ -109,6 +128,7 @@ craft-exr = { path = "crates/exr" }
craft-flags = { path = "crates/flags" }
craft-font-catalog = { path = "crates/font-catalog" }
craft-font-manager = { path = "crates/font-manager" }
craft-font-os-windows = { path = "crates/font-os-windows" }
craft-font-store = { path = "crates/font-store" }
craft-gainmap = { path = "crates/gainmap" }
craft-flow = { path = "crates/flow" }
@@ -116,22 +136,30 @@ craft-gcode = { path = "crates/gcode" }
craft-gif = { path = "crates/gif" }
craft-hdr = { path = "crates/hdr" }
craft-mesh = { path = "crates/mesh" }
craft-mesh-ops = { path = "crates/mesh-ops" }
craft-html = { path = "crates/html" }
craft-ipp = { path = "crates/ipp" }
craft-heif = { path = "crates/heif" }
craft-fig = { path = "crates/fig" }
craft-fonts-build = { path = "crates/fonts-build" }
craft-font-subset = { path = "crates/font-subset" }
# The HarfBuzz subsetter from storytold's HarfBuzz fork (branch rust-subset-15.0.0: HarfBuzz 15.0.0 plus rust/harfbuzz-subset-sys).
harfbuzz-subset-sys = { git = "https://github.com/storytold/harfbuzz.git", rev = "f32ed1e548eaa8852bff47e49a90629a013a2faa" }
craft-host = { path = "crates/host" }
craft-gpu = { path = "crates/gpu" }
craft-gpu-null = { path = "crates/gpu-null" }
craft-gpu-providers = { path = "crates/gpu-providers" }
craft-gpu-wgpu = { path = "crates/gpu-wgpu" }
craft-i18n = { path = "crates/i18n" }
craft-i18n-build = { path = "crates/i18n-build" }
craft-ipc = { path = "crates/ipc" }
craft-idml = { path = "crates/idml" }
craft-indd = { path = "crates/indd" }
craft-jmap = { path = "crates/jmap" }
craft-ical = { path = "crates/ical" }
craft-imaging = { path = "crates/imaging" }
craft-jpeg = { path = "crates/jpeg" }
craft-control = { path = "crates/control" }
craft-control-protocol = { path = "crates/control-protocol" }
craft-jsonrpc = { path = "crates/jsonrpc" }
craft-mcp = { path = "crates/mcp" }
@@ -140,6 +168,7 @@ craft-kiwi = { path = "crates/kiwi" }
craft-keymap = { path = "crates/keymap" }
craft-assuan = { path = "crates/assuan" }
craft-kra = { path = "crates/kra" }
craft-layers = { path = "crates/layers" }
craft-audio = { path = "crates/audio" }
craft-latex = { path = "crates/latex" }
craft-markdown = { path = "crates/markdown" }
@@ -149,6 +178,7 @@ craft-math = { path = "crates/math" }
craft-media = { path = "crates/media", default-features = false }
craft-media-source = { path = "crates/media-source" }
craft-materialx = { path = "crates/materialx" }
craft-material-graph = { path = "crates/material-graph" }
craft-media-testkit = { path = "crates/media-testkit" }
craft-midi = { path = "crates/midi" }
craft-sf2 = { path = "crates/sf2" }
@@ -171,6 +201,7 @@ craft-pcraft-bundle = { path = "crates/pcraft-bundle" }
craft-pkcs7 = { path = "crates/pkcs7" }
craft-plotter = { path = "crates/plotter" }
craft-prepress = { path = "crates/prepress" }
craft-pages = { path = "crates/pages" }
craft-press-print = { path = "crates/press-print" }
craft-print = { path = "crates/print" }
craft-proof = { path = "crates/proof" }
@@ -187,7 +218,9 @@ craft-develop = { path = "crates/develop" }
craft-develop-model = { path = "crates/develop-model" }
craft-sheet = { path = "crates/sheet" }
craft-sketch = { path = "crates/sketch" }
craft-review = { path = "crates/review" }
craft-settings = { path = "crates/settings" }
craft-figcraft-format = { path = "crates/figcraft-format" }
craft-scraft-format = { path = "crates/scraft-format" }
craft-time = { path = "crates/time" }
craft-silhouette-studio = { path = "crates/silhouette-studio" }
@@ -201,11 +234,25 @@ craft-testkit = { path = "crates/testkit" }
craft-text = { path = "crates/text" }
craft-tcraft = { path = "crates/tcraft" }
craft-texture = { path = "crates/texture" }
craft-pbr = { path = "crates/pbr" }
craft-tga = { path = "crates/tga" }
craft-timeline = { path = "crates/timeline" }
craft-tiff = { path = "crates/tiff" }
craft-metadata = { path = "crates/metadata" }
craft-table = { path = "crates/table" }
craft-theme = { path = "crates/theme" }
craft-theme-editor = { path = "crates/theme-editor" }
craft-theme-store = { path = "crates/theme-store" }
craft-tracked = { path = "crates/tracked" }
craft-ui = { path = "crates/ui" }
craft-ui-canvas = { path = "crates/ui-canvas" }
craft-ui-contract = { path = "crates/ui-contract" }
craft-ui-panels = { path = "crates/ui-panels" }
craft-ui-patterns = { path = "crates/ui-patterns" }
craft-ui-shell = { path = "crates/ui-shell" }
craft-ui-test-kit = { path = "crates/ui-test-kit" }
craft-ui-widgets = { path = "crates/ui-widgets" }
craft-ui-macros = { path = "crates/ui-macros" }
craft-update = { path = "crates/update" }
craft-vcard = { path = "crates/vcard" }
craft-vectorcraft-format = { path = "crates/vectorcraft-format" }
@@ -221,20 +268,28 @@ craft-zip = { path = "crates/zip" }
craft-y4m = { path = "crates/y4m" }
craft-sniff = { path = "crates/sniff" }
craft-tar = { path = "crates/tar" }
craft-format = { path = "crates/format" }
craft-mcp-server = { path = "crates/mcp-server" }
craft-epub = { path = "crates/epub" }
craft-ews = { path = "crates/ews" }
craft-video = { path = "crates/video" }
craft-web-api = { path = "crates/web-api" }
craft-window = { path = "crates/window" }
# egui's colour types alone, for crates that convert to and from them without egui.
ecolor = { version = "0.37", default-features = false }
craft-web-host = { path = "crates/web-host" }
craft-webp = { path = "crates/webp" }
egui = { version = "0.37", default-features = false }
bitflags = "2"
md5 = { package = "md-5", version = "0.10", default-features = false }
jxl-oxide = { version = "0.12", default-features = false }
jixel = "=0.3.4"
rayon = "1"
scoped-tls = "1"
smallvec = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
typeid = "1"
proptest = "1"
# Character sets of the WHATWG Encoding Standard (craft-mime). (Apache-2.0 OR MIT) AND BSD-3-Clause.
encoding_rs = "0.8"
@@ -270,20 +325,21 @@ hayro-postscript = { path = "vendor/hayro-postscript" }
linesweeper = { path = "vendor/linesweeper" }
vello_common = { path = "vendor/vello_common" }
vello_cpu = { path = "vendor/vello_cpu" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
kurbo = { path = "vendor/kurbo" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
emath = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "932a73b28560acb1a695533307b2cd0d66a42081" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
# symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid
+64 -4
View File
@@ -63,7 +63,17 @@ craft-proof Language data, embedded at build time from craft-i18n's language-dat
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
mikktspace 0.3.0 (https://crates.io/crates/mikktspace/0.3.0), a dependency of crates/mesh-ops,
is MIT OR Apache-2.0. Its src/generated.rs, a translation of Morten S. Mikkelsen's C
MikkTSpace, carries that original's 2011 zlib-style notice, which must not be removed or
altered; crates/mesh-ops/ATTRIBUTION.md reproduces it in full.
crates/text/assets/hyphen/en-us.pat: CC0-1.0, trained from en-us.dic by DesignCraft's trainer.
crates/text/assets/spell/en-us-scowl-50.txt.deflate: SCOWL (Spell Checker Oriented Word Lists)
2020.12.07, size 50, American English, Copyright 2000-2018 by Kevin Atkinson, http://wordlist.aspell.net/.
Permission to use, copy, modify, distribute and sell these word lists is granted without fee
provided the copyright and permission notice appears in all copies; the full notice, with the
notices of the lists SCOWL draws on, is in crates/text/assets/spell/LICENSE-SCOWL.txt and must
ship with any application that enables craft-text's `spell` feature.
Hyphenation patterns for other languages, embedded through the hypher crate only when the
matching craft-text feature is enabled (none are by default). They come from hyph-utf8,
https://github.com/hyphenation/tex-hyphen, as packaged in https://github.com/typst/hypher
@@ -223,6 +233,37 @@ The colour management module in crates/cms is extracted from:
Licensed MIT OR Apache-2.0. Its generated ICC profile is dedicated to the public domain
(CC0-1.0); see ATTRIBUTION.md.
The mesh operations in crates/mesh-ops are moved from:
- TextureCraft, crates/geom (src/mesh.rs, bvh.rs, primitives.rs, gbuffer.rs, unwrap.rs,
camera.rs and their tests), revision 386630ee85cb22679295b24013575d1aecb39ad2.
https://github.com/storytold/texturecraft
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
- MaterialCraft, crates/geom/src/mesh.rs (subdivision and its test), revision
3133062968b8a1566eda12a357cb06062db16687.
https://github.com/storytold/materialcraft
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
All licensed MIT OR Apache-2.0.
The image-based lighting in crates/pbr (craft-pbr) is adapted from:
- TextureCraft, crates/render/src/ibl.rs, revision fe8ee1bdb0243335560d3e726633cc0433ee99fc,
copied without its tests to crates/pbr/tests/it/reference/texturecraft.rs.
https://github.com/storytold/texturecraft
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
- MaterialCraft, crates/render/src/ibl.rs, revision 4ff5af9af7371613ee37b186e03caf49ee6dbd88,
whose differing parts are copied to crates/pbr/tests/it/reference/materialcraft.rs.
https://github.com/storytold/materialcraft
Copyright (c) 2026 ArtCraft Team and the MaterialCraft contributors.
The BRDF, environment BRDF and default environment in crates/pbr are adapted from:
- EffectCraft, crates/render/src/three_d/adv/shade.rs and adv/scene.rs, revision
41da144555a1c8ddbbe94876a00259832322d00c, whose shading functions and default environment
are copied to crates/pbr/tests/it/reference/effectcraft.rs.
https://github.com/storytold/effectcraft
Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors.
The WGSL text in crates/pbr/src/shade.wgsl is adapted from:
- EffectCraft, crates/gpu/src/shaders/advanced3d.wgsl, revision
f4d45dfef3a280d96aff1d4eb5f1950160adefc2 (above).
All four sources are licensed MIT OR Apache-2.0. crates/pbr/README.md lists the changes from them.
Optional PDF writer
Krilla 0.8.2 (https://github.com/LaurenzV/krilla), MIT OR Apache-2.0.
@@ -262,10 +303,18 @@ applications retain their own document-font selection and licensing policy.
linesweeper
linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in
vendor/linesweeper with its upstream license files and local patches, to src/sweep/sweep_line.rs,
src/curve/mod.rs, src/curve/line.rs and docs/sweep.typ. Its manifest names Joe Neeman as author, and
its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/linesweeper/README.craft.md and
vendor/linesweeper/SOURCE.json for provenance, the local patches and the files left out.
vendor/linesweeper with its upstream license files and local changes. Its manifest names Joe Neeman
as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See
vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local
changes and the files left out.
kurbo
kurbo 0.13.1 (https://crates.io/crates/kurbo/0.13.1, https://github.com/linebender/kurbo), MIT OR
Apache-2.0, is stored in vendor/kurbo with its upstream license files and local patches, to
src/stroke.rs. Its source files carry "Copyright <year> the Kurbo Authors" lines (2018 to 2026),
and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See vendor/kurbo/README.craft.md and
vendor/kurbo/SOURCE.json for provenance and the local patches.
Platform lifecycle source provenance
@@ -426,3 +475,14 @@ Original src/avx2/fdct.rs opening notice
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
The .cdr reader (crates/cdr, moved from VectorCraft crates/cdr) reads the record layouts that the
Kaitai Struct specification coreldraw_cdr.ksy (https://github.com/kaitai-io/coreldraw_cdr.ksy,
MIT License) and its fork by Zach Wolfe (https://github.com/filestar/coreldraw_cdr.ksy, branch
new_stuff, MIT License) describe. No part of either specification is copied into the crate; the
license text is in crates/cdr/LICENSE-kaitai.txt.
The Y4M range-backed source in crates/media-source/src/y4m.rs adapts FilmCraft's
original implementation (3f137a7ed420cac79b32145f5243b7f98b31f71c), licensed
MIT OR Apache-2.0. Source notice retained:
Copyright (c) 2026 ArtCraft Team and the FilmCraft contributors.
+137 -37
View File
@@ -56,36 +56,47 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
## Libraries
- [`craft-platform`](crates/platform/README.md): optional native dialog lifecycle, Linux/BSD desktop appearance observation and browser download ownership; application policy stays in the apps.
- [`craft-aep`](crates/aep/README.md): After Effects projects: the `.aep` (RIFX) and `.aepx`
container as a lossless chunk tree that writes back byte for byte, and a typed, read-only view
of compositions, layers, properties, keyframes, effects, masks, shapes, text and footage.
Clean room, from EffectCraft. Mapping onto an app's document stays in the app.
- [`craft-ai`](crates/ai/README.md) *(spec)*: AI provider abstraction — BYO API keys (OpenAI-compatible) and one-click curated local models with capability probing, resumable checksummed downloads, and document segmentation that protects markup while translating prose;
- [`craft-ai-core`](crates/ai-core/README.md): the data model and contract for AI in the Craft Apps (connections, models, tools, requests, jobs, consent, history, route spec). Pure, no I/O, wasm-safe. Contract in [docs/ai-shared-layer.md](docs/ai-shared-layer.md).
- [`craft-pe`](crates/pe/src/lib.rs): PE/COFF headers (`.exe`, `.dll`, `.sys`, `.efi`) from untrusted bytes, from Craft Anything: the COFF header, PE32/PE32+ optional header with its data directories bounded by the header's real size, the section table, RVA-to-file mapping and the decoded Rich header.
- [`craft-pdf`](crates/pdf/README.md): independently optional PDF parsing, interpretation, rasterization and guarded authoring. Apps retain layout, fonts, editing and export policy; writer-only consumers do not enable the shared reader.
- [`craft-pdn`](crates/pdn/README.md): Paint.NET documents (`.pdn`, PDN3), read: the layer list, blend modes and chunked gzip pixel blocks, with a data-only MS-NRBF (.NET binary serialization) reader. From PhotoCraft.
- [`craft-aaf`](crates/aaf/README.md): clean-room AAF (Edit Protocol, structured storage) and OMF Interchange 2.0 (Bento) readers and writers over one mob-style composition model with exact times, clip gain, markers, nested compositions and embedded PCM essence. From FilmCraft.
- [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped.
- [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app.
- [`craft-automation`](crates/automation/README.md): drive a running app from tests, agents and the CLI: control channel, screenshot queue, frame profiler and trace (native only); recorded actions, their playback and the Actions panel (every target).
- [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite.
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft.
- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), the asset attribution check, an optional slot lock held across processes, an optional per-step JSON report, and PNG images packed into `.ico` and `.icns` files. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft; icon packing for DeckCraft, CADCraft, craft-launcher and MaterialCraft.
- [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral
model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and
TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from
FilmCraft.
- [`craft-cdr`](crates/cdr/README.md): bounded reader and writer of `.cdr` drawings: versions 1 to
27 and `.cmx` files read into one drawing model (pages, layers, groups, shapes, fills and
outlines), and version 15 `.cdr` files written.
- [`craft-cfb`](crates/cfb/README.md): clean-room Compound File Binary ([MS-CFB], OLE structured
storage) reader and writer: the container of legacy Office files, Outlook messages, encrypted
OOXML packages and AAF. Bounded on hostile input; what the streams hold stays with each format.
- [`craft-dav`](crates/dav/README.md): WebDAV multistatus documents (RFC 4918) with the CalDAV and
CardDAV namespaces, from MailCraft: read fail-closed into a bounded `craft-xml` tree with fixed
prefixes, and the successful properties of each response. No I/O.
- [`craft-browse`](crates/browse/README.md): browsing: standard folders, volumes and lazy folder
listings, linked-file statuses kept current, file thumbnails decoded by the app in jobs, and
(`ui` feature) the tile grid, media bin, places tree, compare tile, links list and relink dialog.
- [`craft-cms`](crates/cms/README.md): pure-Rust ICC v2/v4 colour management: profile parsing
and writing, transforms, rendering intents, black point compensation, soft proofing, gamut
checks, 3D LUTs and built-in profiles (sRGB, Display P3, synthetic coated CMYK and others).
- [`craft-crs`](crates/crs/README.md): Adobe Camera Raw settings (the `crs:` namespace of an XMP packet or `.xmp` sidecar, read through craft-metadata): the settings by name, numbers, tone curve points, local corrections and the crop, read and written. From PhotoCraft.
- [`craft-codepage`](crates/codepage/README.md): legacy 8-bit code pages, one table each: the single-byte Windows pages, Mac OS Roman and fifteen DOS pages, keyed by Windows code page number, with the RTF/Word font charsets. craft-rtf, craft-dxf and craft-mime decode through it.
- [`craft-color-ui`](crates/color-ui/README.md): colour picker, wells, swatch tables, ramps and the hex
field; the Color Picker dialog, droppers, eyedropper, samplers, screen picker, Color and Swatches
panels (`ui` feature); swatch files, the display transform and harmonies.
- [`craft-crw`](crates/crw/README.md): clean-room Canon CRW (CIFF) raw decoder, from LightCraft:
the heap container, the entropy coding derived by black-box analysis (frozen code tables), sensor
black and white levels and as-shot white balance. The complete derivation record (plan, sources
@@ -108,6 +119,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-docpath`](crates/docpath/src/lib.rs): decides whether a path or `file:` URL stored in a
document may be opened. Paths stored in documents are followed only when they are local or on the
document's own network share; other network paths, device paths and non-file URLs are refused.
`links` keeps a document's linked files: their status, the identity check, folder remaps and
folder searches.
- [`craft-dpx`](crates/dpx/src/lib.rs): DPX (SMPTE ST 268) and Kodak Cineon frames, from PhotoCraft,
FilmCraft and EffectCraft: header fields and code values at 8, 10, 12 and 16 bits in both byte
orders, filled and packed, RGB, RGBA, ABGR, luma and Y'CbCr descriptors, and a writer for both
@@ -116,6 +129,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
EMU units and `a:xfrm`, colours with theme slots and colour transforms, preset shape outlines
(`a:prstGeom`), custom geometry with guide formulas (`a:custGeom`) and preset text warps
(`a:prstTxWarp`). From DeckCraft. Takes `craft-xml` trees; packages stay with each format.
- [`craft-ease`](crates/ease/README.md): easing curves, keyed tracks, constant-speed motion paths
and damped springs for animation: named eases, CSS `cubic-bezier()`, speed and influence,
editable custom and sampled curves, hold keys and a spring stepped by its exact solution.
From AniCraft and EffectCraft. No dependencies without the optional `serde` feature.
- [`craft-elf`](crates/elf/src/lib.rs): ELF program headers and dynamic section entries from untrusted bytes, from Craft Anything: 32- or 64-bit in either byte order, bounded counts and overflow-checked offsets, virtual-address-to-file mapping through `PT_LOAD`, and segment, permission and dynamic tag names.
- [`craft-eps`](crates/eps/README.md): Encapsulated PostScript files as a container: the binary
preview header (read and write), the DSC header comments and bounding boxes (also `(atend)`),
@@ -124,6 +141,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-docx`](crates/docx/README.md): DOCX (WordprocessingML) read and written on `craft-wordmodel`, with
Word XML (Flat OPC) and Word 2003 XML, password-protected packages and Restrict Editing hashes.
WordCraft's DOCX crate on `craft-opc`, `craft-xml` and `craft-offcrypto`.
- [`craft-draw`](crates/draw/README.md): vector and shape tools; the gradient editor and
on-canvas gradient overlay, the pen and path overlays, the crop frame and perspective crop, and the
free transform box and fields (`ui` feature).
- [`craft-dxf`](crates/dxf/src/lib.rs): DXF tag reader and writer, from CADCraft: ASCII and
binary DXF as (group code, value) tags, split into sections and entities, with pre-2007 code
pages and version detection, and written back; and `model`, the drawing above the tags (header
@@ -158,14 +178,20 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
decoding (scan lines, tiles, every compression of the `exr` crate) and writing.
- [`craft-flags`](crates/flags/README.md): Feature flags shared by the Craft apps and the ArtCraft Launcher: one per-user `ArtCraft/flags.toml`, a `CRAFT_FLAGS` override, every flag off by default (`AI-MCP`, `AI-MODELS`).
- [`craft-flow`](crates/flow/README.md): the flow model every text format maps to (paragraphs with a kind, lists and formatted spans; tables; pictures, fields, notes, equations), converted to and from a craft-wordmodel `Document`.
- [`craft-imaging`](crates/imaging/README.md): raster image editing; the scope counting (every
target) and, with the `ui` feature, the warp grid, the levels editor, the Channels panel and the
scope panel with its clipping overlay.
- [`craft-font-catalog`](crates/font-catalog/README.md): the installed fonts on every platform
(font folders, fontconfig and Flatpak host folders, CoreText, DirectWrite, the font store),
lookup by family, style, localized, legacy, full and PostScript names, family loads shared
between threads, and rescans when fonts are installed or removed.
- [`craft-font-manager`](crates/font-manager/README.md): Craft Font Manager as a library: search
and filters over the Google Fonts index, installed fonts by family, the font store interface,
and (`egui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab
and (`ui` feature) `FontsPanel`, the whole interface as one panel for the launcher's Fonts tab
and the standalone app.
- [`craft-font-os-windows`](crates/font-os-windows/src/lib.rs): the Win32 calls `craft-font-store`
needs on Windows to make a font available to every app of the user (the per-user font
registry, `AddFontResourceW`, `WM_FONTCHANGE`), behind a safe API.
- [`craft-font-store`](crates/font-store/README.md): the suite's font store: the pinned Google
Fonts and Noto indexes plus indexes the user adds (never curated), exact lookup by family and
style or PostScript name, and installs from each source's URLs (jsDelivr, then raw GitHub)
@@ -185,6 +211,17 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
every frame's position, delay, disposal and transparent colour, the loop count and the first
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
a file can hold the picture it declares before a decoder runs.
- [`craft-gpu-yuv`](crates/gpu-yuv/README.md): the `craft.yuv` GPU provider. It converts RGBA to
NV12, P010 and I420, scaled to the output size, in BT.601, BT.709 and BT.2020 at limited or full
range, through the `craft-gpu` job registry on the null context or on a device. Each output texel
averages the part of the source it covers. The crate also has the render passes for a caller's
own encoder, read-back layouts with unpacking to a packed frame, and the same conversion on the
CPU. Encoders and scopes stay in each app.
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
low power, a named adapter that survives a reordered list and a driver update, or software;
corrections for drivers that crash; the next adapter and then a software one when a device fails
to open; a capability report; device-loss and error recording without panics; and what to reopen
after a loss. Settings pages and the window stay in each app.
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
@@ -200,6 +237,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
lookup with fallback (`pt-br` → `pt` → English), plurals, language names, the system locale and
a pseudo locale. The catalogs stay a fully optional build input; apps keep `tl!` and their
language setting.
- [`craft-i18n-build`](crates/i18n-build/README.md): embeds the optional craft-i18n catalogs
from an app's `build.rs` (`CRAFT_I18N_DIR`, `CRAFT_I18N_REQUIRED`) as the table `craft-i18n`
reads, with each regional locale's parent and the app's own catalogs merged in. No
dependencies.
- [`craft-raw`](crates/raw/README.md): camera raw files, the file-format layer, from LightCraft with
what PhotoCraft's and FilmCraft's readers added: container parsing and decompression to a neutral
raw image (samples, CFA, black and white levels, active area, crop, orientation, colour tags,
@@ -224,13 +265,8 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
CCITT Group 3 and 4 decoding and Group 4 encoding, JBIG2 decoding and lossless encoding. Every
decoder is bounded and returns its partial output on damage. From PdfCraft; a PDF filter chain
is built on it in `craft-pdf`.
- [`craft-timeline`](crates/timeline/README.md): editorial timeline interchange: exact media time and SMPTE timecode, import/export reports, media path and `file://` URL handling, Avid Log Exchange (ALE) and CMX 3600 EDL documents, format detection. From FilmCraft.
- [`craft-time`](crates/time/README.md): exact rational ticks and SMPTE time across media, with a `soundcraft` compatibility module retaining SoundCraft's sample-index timebase, tempo maps, grids and session serialization semantics.
- [`craft-scraft-format`](crates/scraft-format/README.md): SoundCraft's typed `.scraft` session schema, versioned reader/writer, hostile-input validation, and `.scraftz` bundle reader/writer. Engine and UI mapping stays in SoundCraft.
- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write,
maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge
that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG,
WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`.
- [`craft-tiff`](crates/tiff/README.md): TIFF and BigTIFF IFD reader and writer, from LightCraft:
every field type, the IFD chain, SubIFDs and Exif/GPS/Interop pointer IFDs, maker-note IFDs
(Canon, Nikon, Sony, Fujifilm, Olympus, Panasonic, Pentax), strip and tile layout. Bounded and
@@ -266,6 +302,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
scopes, conflicts, user overrides stored through craft-settings and import of other
applications' shortcut sets. Command catalogs, file readers and the shortcut editor UI stay
in each app.
- [`craft-layers`](crates/layers/README.md): the Layers panel over the app's `LayerTree`: rows
with thumbnails and masks, blend, opacity, lock and fill rows, the filter bar, Layers Panel
Options, drag and drop, and events the app applies with its own commands and undo. UI-only.
- [`craft-audio`](crates/audio/README.md): audio file I/O and codecs (WAV, AIFF, FLAC, AAC, Opus,
AC-3/E-AC-3, MP1/MP2, MP3 encoding), streaming and seeking, and packet decoding for any demuxer. See its
README for formats and features.
@@ -274,7 +313,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-markdown`](crates/markdown/README.md): Markdown read and written (a CommonMark subset with GitHub tables and strikethrough), to and from the craft-flow model.
- [`craft-math`](crates/math/README.md): equations as one tree (the Office Math object model) with its syntaxes, read and written: OMML, presentation MathML, LaTeX math and the UnicodeMath linear format.
- [`craft-media`](crates/media/README.md): bit-level I/O (`bitstream`), clean-room MP4/MOV
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`) and
(`isobmff`), Matroska/WebM (`matroska`) and MXF (`mxf`) demuxers and muxers, Ogg (`ogg`), AVI (`avi`), Bink (`bink`) and
MPEG-TS/PS (`mpegts`) demuxers, from FilmCraft, a Sierra VMD (`vmd`) demuxer, and an ISO BMFF box reader. Containers only; codecs are in `craft-audio`, and
video codecs will go in a separate crate.
- [`craft-lottie`](crates/lottie/README.md): Lottie (Bodymovin) JSON: the document model of
@@ -290,6 +329,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
of polygons with per-corner indices, materials, a node hierarchy): STL, OBJ with MTL, PLY,
glTF 2.0 / GLB, FBX and 3MF, one feature each. Readers are bounded by `Limits`, never open a file
themselves and never panic. Carved from EffectCraft, SolidCraft, TextureCraft and MaterialCraft.
- [`craft-mesh-ops`](crates/mesh-ops/README.md): operations on triangle meshes: smooth normals,
MikkTSpace tangents, welding, UV unwrapping, a UV-space G-buffer, primitives with UVs and a
BVH for ray casts, and an orbit camera. From TextureCraft and MaterialCraft.
- [`craft-midi`](crates/midi/README.md): Standard MIDI Files: a bounded reader for formats 0, 1 and
2 and a format-1 writer, over a neutral model of notes and channel events in ticks at 960 per
quarter note. From SoundCraft.
@@ -310,6 +352,10 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-opc`](crates/opc/README.md): Open Packaging Conventions, the ZIP container of DOCX, XLSX and PPTX
files: bounded readers (every part up front, or on demand), part names, relationships, content
types and a deterministic package writer. What the parts hold stays with each format's crate.
- [`craft-pages`](crates/pages/README.md): pages for the document apps: page layout and fit modes,
paper sizes and page setup, page ranges and numbering; with `ui`, the page view, thumbnails, Page
Setup, margin handles, header and footer zones, text selection, reading view, page list and
document tables. The document, its layout and rendering stay in each app.
- [`craft-pcraft-format`](crates/pcraft-format/README.md): the envelope of PhotoCraft's `.pcraft`
bundle: `Manifest<D>` with the document as a type parameter, `TileRef`, the entry paths, the
manifest decode limits and the migration runner. The document model stays in PhotoCraft.
@@ -339,20 +385,25 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
craft-i18n's `language-data/`, embedded at build time from `CRAFT_I18N_DIR`: English and the
carry-over locales by default, the set `CRAFT_PROOF_EMBED` names otherwise (`en` for English
only); other languages come from installed Language packs.
- [`craft-pst`](crates/pst/README.md): Outlook personal folders files (`.pst`, [MS-PST]) read over any
`Read + Seek`, from MailCraft: the node database, property and table contexts, folders, messages,
recipients, attachments, attached messages and named properties, ANSI and Unicode, encoded or not,
with a password. Salvages damaged files. Bounded and panic-free on hostile input. What an item
means stays in each app.
- [`craft-quit`](crates/quit/src/lib.rs): native macOS quit, egui close handling and an optional
app menu. Unsaved-document decisions and save prompts stay in each app.
- [`craft-quit`](crates/quit/README.md): native macOS quit, a window close held for unsaved
documents, the Quit menu item id and the unsaved-changes question one document at a time
(`CloseGuard`). The prompt and the saving stay in each app.
- [`craft-rtf`](crates/rtf/README.md): Rich Text Format: a tokenizer, text decoding in the file's code pages
(`\uN`, `\'hh`, single-byte and East Asian multibyte pages), escaping and dates, and a reader and writer
for a small neutral model (paragraphs, character formatting, outline levels, tables).
- [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations. Policy in [docs/settings-storage.md](docs/settings-storage.md).
- [`craft-review`](crates/review/README.md): review: the comments panel, comment pins, thread
popover and composer, Acrobat's annotation tool, the signature pad, version history and the
revisions panel, presence, voting, cursor chat and join over the app's own transport (`ui`
feature).
- [`craft-settings`](crates/settings/README.md): `config.toml` settings storage for every app: platform folders, portable mode and overrides, atomic saves while running, backup, damaged-file recovery and schema migrations, plus remembered dialog options and preset folders (also on wasm32). Policy in [docs/settings-storage.md](docs/settings-storage.md).
- [`craft-shared-vec`](crates/shared-vec/README.md): an ordered, indexed list whose clones share storage, for document trees kept in an undo history: an edit copies the blocks on its path instead of the whole list, and `bytes_not_in` counts what keeping two versions costs. Reads and writes as a plain sequence with `serde`.
- [`craft-sheet`](crates/sheet/README.md): spreadsheet vocabulary shared by `craft-xls`, `craft-xlsx` and `craft-ods`: cell positions and A1 text, cell values and error values, sheet-name quoting, Excel's built-in number formats and indexed colour palette. Not a file format; no dependencies.
- [`craft-sf2`](crates/sf2/README.md): SoundFont 2 (`.sf2`) reader: the sample pool and, per preset, the key and velocity regions a note sounds, with tuning, loop points, pan, level and volume envelope resolved from the preset and instrument zones. Bounded on hostile input. From LoopCraft.
- [`craft-silhouette-studio`](crates/silhouette-studio/src/lib.rs): bounded, fail-closed reader for Silhouette Studio `.studio` and `.studio3` documents: outlines, line colours and page size in millimetres. Protected designs are refused.
@@ -370,27 +421,41 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency.
- [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`,
`color` and `write`; re-exports them for existing users.
- [`craft-table`](crates/table/README.md): spreadsheet widgets: the cell grid with Excel's
keys, outline bands, the PivotTable field list, the condition builder, chart painting, slicers,
reference picking, selection statistics, error tags and filter buttons (`ui` feature).
- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module
reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals
out of range, and `std::time::Instant` in code the web build runs. Its `deadline` module fails a test
whose body runs past a limit, or whose condition does not hold in time; a variable the caller names
replaces each limit. Its `hostile` module runs a parser on every truncation and on seeded damaged
copies of a valid input, and fails the test with the case that panicked or did not finish. Not
published.
out of range, and `std::time::Instant` in code the web build runs. Its `fonts` module makes test fonts
from font bytes the caller supplies: a face with a renamed family and a TrueType collection. Its
`deadline` module fails a test whose body runs past a limit, or whose condition does not hold in time;
a variable the caller names replaces each limit. Its `hostile` module runs a parser on every truncation
and on seeded damaged copies of a valid input, and fails the test with the case that panicked or did
not finish. Its `rng` module holds two seeded generators for repeatable test input. Its `skip` module
prints a `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the
test when the variable the caller names is `1`. Any other value of that variable except empty fails
the test as a configuration error. Its `corpus` module (the `corpus` feature) checks a corpus folder
against a pinned SHA-256 list. Its `fixtures` module (native targets only) generates test fixtures
under `target/fixtures` and publishes each one under a lock. Not published.
- [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds
hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns
for 47 more languages (one cargo feature each).
for 47 more languages (one cargo feature each). With `ui`, the canvas text editor, Character and
Paragraph controls, text style panels and Check Spelling dialog, and the paged-text controls
(ruler, Tabs, Paragraph, Columns and Hyperlink dialogs, notes editor, find); `spell` and `find`
(regex) are features.
- [`craft-texture`](crates/texture/README.md): linear float image planes, gray or RGBA, with
nearest and bilinear sampling that repeats or clamps, resizing and display conversion. Sizes are
bounded by `Limits`. From MaterialCraft.
- [`craft-ui`](crates/ui/README.md): SVG catalogs, icon buttons, tabs, pane controls, transactional docking, print settings and theme helpers for egui frontends;
- [`craft-ai`](crates/ai/README.md) *(spec)*: AI provider abstraction — BYO API keys (OpenAI-compatible) and one-click curated local models with capability probing, resumable checksummed downloads, and document segmentation that protects markup while translating prose;
assets, themes, localization and command handling stay in each app. Requires Rust 1.95 or later.
- [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read
(legacy character sets, quoted-printable, labels and Apple label groups, `KEY` certificates and
OpenPGP public keys), vCard 3.0 written. Bounded and panic-free on hostile input. The mapping onto
an app's contact type stays in each app.
nearest and bilinear sampling that repeats or clamps, resizing and display conversion, and
(optional features) PNG, TIFF, Radiance HDR and OpenEXR decoding that keeps 16-bit and float
samples. Sizes are bounded by `Limits`. From MaterialCraft.
- [`craft-timeline`](crates/timeline/README.md): timelines: exact media time, frame rates,
timecode, the playback clock, a frame cache and frame server, and editorial interchange (ALE,
CMX 3600 EDL, Final Cut Pro 7 XML, FCPXML, OpenTimelineIO), all egui-free; the timeline panel,
ruler, clips, keyframe lanes, graph editor, transport, timecode fields, preview, overview and
render queue (`ui` feature).
- [`craft-metadata`](crates/metadata/README.md): photo metadata, from LightCraft: EXIF (read and write,
maker-note lens and focus point, every tag by name), IPTC-IIM, XMP packets (read, write, and a merge
that keeps what another program wrote), GPX track logs, and the blocks that carry them in JPEG, PNG,
WebP, TIFF-based, RAF and CR3 files. One `Metadata` model for all of them. Built on `craft-tiff`.
- [`craft-vectorcraft-format`](crates/vectorcraft-format/README.md): the envelope of VectorCraft's
`.vectorcraft` file: its members, versions, embedded images and the data after the JSON, with the
document as a type parameter. The document and its migrations stay in VectorCraft.
@@ -421,12 +486,47 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
- [`craft-xcf`](crates/xcf/README.md): GIMP XCF images (`.xcf`, `.xcf.gz`), read: header, properties, parasites, layers with their item paths, channels, and tiled pixels (uncompressed, RLE, zlib) at every precision, under a caller's byte budget. From PhotoCraft.
- [`craft-xml`](crates/xml/README.md): bounded XML for hostile input: an owned element tree with limits on size, depth, nodes and attributes, streaming of repeated elements, namespace handling (as written, by local name, or canonical prefixes by URI), escaping and a writer. No DTDs and no entity expansion.
- [`craft-zip`](crates/zip/README.md): ZIP archives from untrusted files: an entry-count check before the archive is indexed (ZIP64 included), entry reads within per-entry and total budgets that count real bytes, duplicate-name detection, a strict structure preflight, and a deterministic stored/deflate writer. The shared ZIP layer for the package formats. With the `lenient` feature, also a reader of the raw bytes without the `zip` crate, from Craft Anything, for inspectors that must describe damaged archives rather than refuse them: the central-directory listing with ZIP64, prepended-stub and multi-volume checks, CP437 and Info-ZIP Unicode Path names, and entry reads (stored, DEFLATE, and bzip2, LZMA, XZ and Zstandard behind `lenient-*` features) checked against the declared size and CRC-32.
- [Shared UI component audit](docs/ui-components-audit.md): source inventory, extraction priorities
and compatibility boundaries across the Craft suite.
- [Theme infrastructure](docs/theme-infrastructure.md): eight-app comparison and the small shared
widget-state styling boundary.
- [Panel docking](docs/ui-docking.md): validated panel moves, floating groups, workspace adapters
and an optional egui docking surface.
## Craft framework
The shared UI layer of the Craft apps: the design system, the UI library on egui, the host convention and the
feature families above. Assets, localization and commands stay in each app. Requires Rust 1.95 or later. Design and
architecture: [docs/craft-framework.md](docs/craft-framework.md).
- [`craft`](crates/craft/README.md): the facade: one dependency, one pin and one import root for an app, with a
feature per crate.
- `craft-ui`: the UI library's facade, which re-exports its six crates under one root (`craft_ui::…`):
- `craft-ui-contract`: runtime, style, fonts, primitives, the component contract, layout and the test kit;
- `craft-ui-widgets`: the components (buttons, choices, fields, lists, menus, pickers, tabs, tables, bars);
- `craft-ui-panels`: sections, dialogs, docking and rails;
- `craft-ui-canvas`: the canvas, its tools and controls, and the full-window dialogs;
- `craft-ui-patterns`: ready-made dialogs, presets, preferences and dock areas;
- `craft-ui-shell`: the app shell, the title bar and the eframe entry point.
- [`craft-vcard`](crates/vcard/README.md): vCard contacts, from MailCraft: vCard 2.1, 3.0 and 4.0 read
(legacy character sets, quoted-printable, labels and Apple label groups, `KEY` certificates and
OpenPGP public keys), vCard 3.0 written. Bounded and panic-free on hostile input. The mapping onto
an app's contact type stays in each app.
- `craft-ui-macros`: the derives and macros of the library (`Component`, `Props`, `ComponentStyle`, `Pattern`,
`CommandSet`, words, stories and trials); use them through `craft-ui`.
- `craft-behavior`: the behaviour cores with no egui: press lifecycle, value drags, navigation, item layouts, edit
events and the dock model.
- [`craft-theme`](crates/theme/README.md) and [`craft-theme-store`](crates/theme-store/README.md): the token model,
the built-in themes and the suite's theme selection ([docs/suite-themes.md](docs/suite-themes.md)).
- [`craft-host`](crates/host/README.md): the services an app installs once and every feature reads.
- `craft-win32`: the window-procedure and window-handle Win32 calls that need `unsafe`, behind a safe API.
- Tools, not shipped in apps: `craft-ui-gallery` (the story viewer), `story-render` (one component's stories to
PNG files), [`craft-design-lint`](crates/design-lint/README.md), `craft-ui-bench`, `craft-ui-test-kit`.
Framework docs:
- [Craft framework](docs/craft-framework.md): the design, installation, architecture, design system, foundations,
components, accessibility, tests, and the migration and landing plan.
- [Development workflow](docs/development.md): the `cl` commands, the one fixed feature set, what not to run
locally, CI coverage, the profiles, the job pool and what a new worktree's first build costs.
- [Writing a component](docs/authoring.md), the [component index](docs/components-index.md), the
[contract API](docs/contract-api.md) and the [glossary](docs/glossary.md).
- [Docking](docs/ui-docking.md): the dock model, `DockArea`, `SplitArea` and `PaneArea`.
- [Dialogs](docs/ui-dialogs.md): `Dialog`, `DialogHost`, the dialog stack and the standard prompts.
## License and credits
+1 -1
View File
@@ -4,5 +4,5 @@ allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
cognitive-complexity-threshold = 30
disallowed-types = [
{ path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" },
{ path = "egui::ComboBox", reason = "use craft_ui::controls::Select: egui's combo box menu can't grow back while open (egui#5225)" },
]
+1 -1
View File
@@ -5,7 +5,7 @@ composition model.
| Module | What |
|---|---|
| `model` | `Document`: compositions (tracks of fillers, source clips and overlapping transitions; clip gain, constant or keyframed; markers; start timecode), nested compositions, and the media `Source`s they reference (file path or embedded PCM, picture size and rate, sound channels / rate / bits, start timecode, markers). Times are exact `craft_timeline::time::Tick`s. |
| `model` | `Document`: compositions (tracks of fillers, source clips and overlapping transitions; clip gain, constant or keyframed; markers; start timecode), nested compositions, and the media `Source`s they reference (file path or embedded PCM, picture size and rate, sound channels / rate / bits, start timecode, markers). Times are exact `craft_timeline::Tick`s. |
| `aaf` | `read`, `write`, `sniff`: AAF Edit Protocol in structured storage (`craft-cfb`). |
| `omf` | `read`, `write`, `sniff`: OMF Interchange 2.0 in a Bento container. Sound only. |
+4 -1
View File
@@ -1,7 +1,7 @@
//! AAF (Advanced Authoring Format) import and export, following the AAF Edit Protocol.
//!
//! Written from the public AMWA specifications: *AAF Object Specification v1.1*, *AAF Low-Level
//! Container Specification v1.0.1* (structured storage mapping, see [`store`]) and *AAF Edit
//! Container Specification v1.0.1* (structured storage mapping) and *AAF Edit
//! Protocol v1.0*; the container is Microsoft's Compound File Binary format ([`craft_cfb`]).
//!
//! A written file holds one top-level **CompositionMob** (Edit Protocol usage code
@@ -37,6 +37,8 @@
//! name), `FilmCraft Frame Size` and `FilmCraft Audio Sample Rate` (on the composition).
mod ids;
pub mod linked_audio;
pub mod properties;
mod read;
pub(crate) mod store;
mod write;
@@ -47,6 +49,7 @@ use crate::{Identity, Report, Result};
/// How to write an AAF file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WriteOptions<'a> {
/// Who the file says made it.
pub identity: Identity<'a>,
/// Write 512-byte sectors (compound file version 3) instead of 4096-byte sectors.
pub small_sectors: bool,
+129
View File
@@ -0,0 +1,129 @@
//! WAV/PCM FileDescriptor metadata, without loading a SourceMob or touching its locators.
use super::ids::{cls, pid};
/// The two audio descriptor classes commonly attached to an external WAV source.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DescriptorKind {
/// A WAVEDescriptor (`.wav` with a RIFF header).
Wave,
/// A PCMDescriptor (raw PCM samples).
Pcm,
}
impl DescriptorKind {
/// Classify a compound-file storage's CLSID in AAF on-disk AUID byte order
/// (little-endian GUID fields, not RFC 4122/network order).
pub fn from_auid_le(class: [u8; 16]) -> Option<Self> {
match class {
cls::WAVE_DESCRIPTOR => Some(Self::Wave),
cls::PCM_DESCRIPTOR => Some(Self::Pcm),
_ => None,
}
}
}
/// One property from an already framed and caller-validated object.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DescriptorProperty<'a> {
/// The object has no such property.
Missing,
/// The property is stored in a form other than a plain data value.
OtherForm,
/// The property's raw value bytes.
Data(&'a [u8]),
}
/// Why a descriptor field is unavailable.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DescriptorFieldError {
/// The descriptor has no such property.
Missing,
/// The property is stored in a form other than a plain data value.
OtherForm,
/// The value is shorter than the field's type.
Truncated,
}
/// A lazy descriptor view over a caller's property store. This neither opens
/// the media file nor determines whether the AAF source is external.
pub struct AudioFileDescriptor<F> {
kind: DescriptorKind,
property: F,
}
impl<'a, F: Fn(u16) -> DescriptorProperty<'a>> AudioFileDescriptor<F> {
/// Supply the property view for this class; the descriptor chooses AAF property IDs.
pub fn new(kind: DescriptorKind, property: F) -> Self {
Self { kind, property }
}
/// `FileDescriptor::SampleRate` as the signed numerator and denominator on
/// the wire. The caller's rational policy (including zero) is not applied.
pub fn sample_rate(&self) -> Result<(i32, i32), DescriptorFieldError> {
let [a, b, c, d, e, f, g, h] = self.bytes(pid::SAMPLE_RATE)?;
Ok((i32::from_le_bytes([a, b, c, d]), i32::from_le_bytes([e, f, g, h])))
}
/// `FileDescriptor::Length` in sample-rate units, before validating clip ranges.
pub fn length(&self) -> Result<i64, DescriptorFieldError> {
self.bytes(pid::FILE_LENGTH).map(i64::from_le_bytes)
}
/// `SoundDescriptor::Channels` for a PCM descriptor. A WAVEDescriptor has
/// no such declared count here; an absent PCM field is also left to the caller.
pub fn pcm_channels(&self) -> Result<Option<u32>, DescriptorFieldError> {
if self.kind == DescriptorKind::Wave {
return Ok(None);
}
match self.bytes(pid::CHANNELS) {
Ok(bytes) => Ok(Some(u32::from_le_bytes(bytes))),
Err(DescriptorFieldError::Missing) => Ok(None),
Err(err) => Err(err),
}
}
fn bytes<const N: usize>(&self, pid: u16) -> Result<[u8; N], DescriptorFieldError> {
match (self.property)(pid) {
DescriptorProperty::Data(data) => data.first_chunk().copied().ok_or(DescriptorFieldError::Truncated),
DescriptorProperty::Missing => Err(DescriptorFieldError::Missing),
DescriptorProperty::OtherForm => Err(DescriptorFieldError::OtherForm),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn descriptor_class_and_little_endian_fields_are_typed() {
assert_eq!(DescriptorKind::from_auid_le([1, 1, 1, 13, 1, 1, 0, 0x48, 6, 14, 43, 52, 2, 6, 1, 1]), Some(DescriptorKind::Pcm));
assert_eq!(DescriptorKind::from_auid_le(cls::WAVE_DESCRIPTOR), Some(DescriptorKind::Wave));
assert_eq!(DescriptorKind::from_auid_le(cls::CDCI_DESCRIPTOR), None);
let file = AudioFileDescriptor::new(DescriptorKind::Pcm, |tag| match tag {
pid::SAMPLE_RATE => DescriptorProperty::Data(&[0x80, 0xbb, 0, 0, 1, 0, 0, 0]),
pid::FILE_LENGTH => DescriptorProperty::Data(&[2, 1, 0, 0, 0, 0, 0, 0, 99]),
pid::CHANNELS => DescriptorProperty::Data(&[2, 0, 0, 0]),
_ => DescriptorProperty::Missing,
});
assert_eq!(file.sample_rate(), Ok((48000, 1)));
assert_eq!(file.length(), Ok(258));
assert_eq!(file.pcm_channels(), Ok(Some(2)));
}
#[test]
fn descriptor_fields_are_lazy_and_distinguish_missing_form_and_short_data() {
let wave = AudioFileDescriptor::new(DescriptorKind::Wave, |tag| match tag {
pid::SAMPLE_RATE => DescriptorProperty::OtherForm,
pid::FILE_LENGTH => DescriptorProperty::Data(&[0; 7]),
_ => panic!("unexpected field read"),
});
assert_eq!(wave.pcm_channels(), Ok(None));
assert_eq!(wave.sample_rate(), Err(DescriptorFieldError::OtherForm));
assert_eq!(wave.length(), Err(DescriptorFieldError::Truncated));
let pcm = AudioFileDescriptor::new(DescriptorKind::Pcm, |_| DescriptorProperty::Missing);
assert_eq!(pcm.pcm_channels(), Ok(None));
assert_eq!(pcm.sample_rate(), Err(DescriptorFieldError::Missing));
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Borrowed little-endian AAF property-stream records, independent of CFB and object policy.
/// One indexed AAF property. The payload borrows the original stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Property<'a> {
/// The property ID (pid).
pub id: u16,
/// The stored form of the value, as the index records it.
pub form: u16,
/// The value's bytes.
pub payload: &'a [u8],
}
/// Malformed property-stream framing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PropertyError {
/// The stream ends before its 4-byte header.
ShortHeader,
/// The header's byte-order mark is not little-endian (0x4c).
UnsupportedByteOrder,
/// The stream ends inside the property index.
TruncatedIndex,
/// A property's length runs past the end of the stream.
TruncatedValue,
}
/// Property-stream record iterator. It does not deduplicate IDs, interpret forms,
/// copy payloads or impose object budgets; those decisions belong to the caller.
#[derive(Clone, Debug)]
pub struct Properties<'a> {
headers: std::slice::Iter<'a, [u8; 6]>,
payload: &'a [u8],
}
impl<'a> Properties<'a> {
/// Validate the header and complete index. Payload extents are checked during
/// iteration; callers can validate all extents before copying by iterating a clone.
pub fn new(stream: &'a [u8]) -> Result<Self, PropertyError> {
let [order, _, lo, hi, tail @ ..] = stream else { return Err(PropertyError::ShortHeader) };
if *order != 0x4c {
return Err(PropertyError::UnsupportedByteOrder);
}
let count = usize::from(u16::from_le_bytes([*lo, *hi]));
let (headers, payload) = tail.split_at_checked(count * 6).ok_or(PropertyError::TruncatedIndex)?;
Ok(Self { headers: headers.as_chunks::<6>().0.iter(), payload })
}
pub(super) fn remaining_count(&self) -> usize {
self.headers.len()
}
// The store checks duplicate IDs before validating the corresponding payload,
// so a record that is both duplicate and truncated retains its old diagnostic.
pub(super) fn next_id(&self) -> Option<u16> {
let [lo, hi, ..] = self.headers.as_slice().first()?;
Some(u16::from_le_bytes([*lo, *hi]))
}
}
impl<'a> Iterator for Properties<'a> {
type Item = Result<Property<'a>, PropertyError>;
fn next(&mut self) -> Option<Self::Item> {
let [id0, id1, form0, form1, len0, len1] = self.headers.next()?;
let len = usize::from(u16::from_le_bytes([*len0, *len1]));
let Some((payload, tail)) = self.payload.split_at_checked(len) else {
self.headers = [].iter();
return Some(Err(PropertyError::TruncatedValue));
};
self.payload = tail;
Some(Ok(Property { id: u16::from_le_bytes([*id0, *id1]), form: u16::from_le_bytes([*form0, *form1]), payload }))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_borrow_ordered_payloads_without_deduplicating() {
let stream = [0x4c, 0x20, 2, 0, 0x55, 0, 0x82, 0, 2, 0, 0x55, 0, 0x22, 0, 1, 0, 9, 8, 7];
let mut records = Properties::new(&stream).unwrap();
assert_eq!(records.remaining_count(), 2);
assert_eq!(records.next_id(), Some(0x55));
let first = records.next().unwrap().unwrap();
assert_eq!(records.next_id(), Some(0x55));
let second = records.next().unwrap().unwrap();
assert_eq!(first, Property { id: 0x55, form: 0x82, payload: &[9, 8] });
assert_eq!(second, Property { id: 0x55, form: 0x22, payload: &[7] });
assert!(std::ptr::eq(first.payload, &stream[16..18]));
assert!(std::ptr::eq(second.payload, &stream[18..19]));
assert!(records.next().is_none());
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
use craft_timeline::time::{FrameRate, Tick};
use craft_timeline::{FrameRate, Tick};
use super::ids::{cls, ddef, def, pid};
use super::store::{self, Auid, Obj, Value, rational_of, utf16_of};
+11 -18
View File
@@ -450,28 +450,21 @@ impl R<'_> {
}
let mut o = Obj::new(e.clsid);
let props = self.stream(entry, "properties")?;
if props.len() < 4 {
return Err(bad("short properties stream"));
}
if props[0] != BYTE_ORDER_LE {
return Err(bad("big-endian AAF files are not supported"));
}
let n = rd_u16(&props, 2).unwrap_or(0) as usize;
let mut at = 4 + n * 6;
if at > props.len() {
return Err(bad("truncated property index"));
}
use super::properties::{Properties, Property, PropertyError};
let framing = |e| match e {
PropertyError::ShortHeader => bad("short properties stream"),
PropertyError::UnsupportedByteOrder => bad("big-endian AAF files are not supported"),
PropertyError::TruncatedIndex => bad("truncated property index"),
PropertyError::TruncatedValue => bad("truncated property value"),
};
let mut records = Properties::new(&props).map_err(framing)?;
// A properties stream can name tens of thousands of ids: do not rescan all earlier ids.
let mut seen = std::collections::HashSet::with_capacity(n);
for i in 0..n {
let (Some(pid), Some(sf), Some(len)) = (rd_u16(&props, 4 + i * 6), rd_u16(&props, 6 + i * 6), rd_u16(&props, 8 + i * 6)) else {
return Err(bad("truncated property index"));
};
let mut seen = std::collections::HashSet::with_capacity(records.remaining_count());
while let Some(pid) = records.next_id() {
if !seen.insert(pid) {
return Err(bad("duplicate property id"));
}
let v = props.get(at..at + len as usize).ok_or_else(|| bad("truncated property value"))?;
at += len as usize;
let Property { form: sf, payload: v, .. } = records.next().ok_or_else(|| bad("truncated property index"))?.map_err(framing)?;
let value = match sf {
SF_STRONG => {
let c = self.child(entry, &utf16_of(v))?;
+2 -2
View File
@@ -3,7 +3,7 @@
use std::collections::HashSet;
use craft_timeline::time::FrameRate;
use craft_timeline::FrameRate;
use super::ids::{self, cls, ddef, def, path, pid};
use super::store::{self, Obj, Value};
@@ -517,7 +517,7 @@ fn sound_source_offsets_use_audio_sample_rate_on_disk() {
_ => None,
})
.unwrap();
assert_eq!(clip.start, craft_timeline::time::FrameRate::FPS_25.tick_of(10));
assert_eq!(clip.start, craft_timeline::FrameRate::FPS_25.tick_of(10));
}
#[test]
+1 -1
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use craft_timeline::time::{FrameRate, Tick};
use craft_timeline::{FrameRate, Tick};
use super::ids::{META_DICTIONARY, ROOT, cls, ddef, def, path, pid};
use super::store::{self, Auid, Obj, Value, rational, utf16z};
+12 -2
View File
@@ -4,7 +4,7 @@
//!
//! - [`model`]: a [`model::Document`] of compositions (tracks of fillers, source clips and
//! overlapping transitions, with clip gain and markers) and the media sources they reference,
//! with exact times ([`craft_timeline::time::Tick`]).
//! with exact times ([`craft_timeline::Tick`]).
//! - [`aaf`]: Advanced Authoring Format, Edit Protocol, in structured storage (`craft-cfb`).
//! - [`omf`]: OMF Interchange 2.0 in a Bento container; sound only.
//!
@@ -19,6 +19,7 @@
//!
//! Input is untrusted: a damaged or crafted file gives an [`Error`] or a [`Report`] entry, never
//! a panic, a hang or an allocation sized by a count in the file.
#![warn(missing_docs)]
pub mod aaf;
pub mod model;
@@ -40,7 +41,12 @@ pub use craft_timeline::time;
pub enum Error {
/// The bytes are not a readable document of the format.
#[error("{format} parse error: {message}")]
Parse { format: &'static str, message: String },
Parse {
/// The format that failed to parse.
format: &'static str,
/// What was wrong.
message: String,
},
/// The document has no composition.
#[error("the document contains no timeline")]
Empty,
@@ -49,15 +55,19 @@ pub enum Error {
Other(String),
}
/// `Result` with this crate's [`Error`].
pub type Result<T> = std::result::Result<T, Error>;
/// Who a written file says made it (the AAF `Identification` object, the OMF `IDNT` object).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Identity<'a> {
/// The company that made the product.
pub company: &'a str,
/// The product name.
pub product: &'a str,
/// The product's version, as text.
pub version: &'a str,
/// The platform the product ran on.
pub platform: &'a str,
/// AAF `ProductID`: an AUID naming the product.
pub product_id: [u8; 16],
+48 -3
View File
@@ -7,12 +7,14 @@
//! mobs and file source mobs: here, a [`Source`] per essence, grouped into one media item by its
//! key. All times are ticks; the format serialisers convert to and from edit units.
use craft_timeline::time::{FrameRate, TICKS_PER_SECOND, Tick};
use craft_timeline::{FrameRate, TICKS_PER_SECOND, Tick};
/// Picture or sound.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CKind {
/// Moving or still images.
Picture,
/// Audio.
Sound,
}
@@ -21,46 +23,63 @@ pub enum CKind {
pub struct Document {
/// The top-level compositions.
pub compositions: Vec<Composition>,
/// The essences the compositions reference.
pub sources: Vec<Source>,
/// Compositions that are only used inside others (nested sequences); a [`Source`] refers to
/// one by its index here. They may nest further.
pub nested: Vec<Composition>,
}
/// How a nested sequence is written. Premiere Pro writes one as a composition of its own in AAF
/// (clips refer to it the way they refer to media) and renders its sound in OMF, which has no
/// One composition: its tracks, markers and timing.
#[derive(Clone, Debug, PartialEq)]
pub struct Composition {
/// The name.
pub name: String,
/// AAF CompositionMob identifier as 64 lowercase hexadecimal digits. OMF has no equivalent.
/// It is a read identity for applications that let a user choose among compositions; writers
/// generate fresh format identifiers and do not preserve it.
pub aaf_mob_id: Option<String>,
/// The edit rate.
pub rate: FrameRate,
/// Sound: samples per second.
pub sample_rate: u32,
/// Picture: width in pixels.
pub width: u32,
/// Picture: height in pixels.
pub height: u32,
/// Start timecode in frames at `rate`.
pub start_tc: i64,
/// Whether the timecode is drop-frame.
pub drop: bool,
/// The tracks, picture and sound.
pub tracks: Vec<CTrack>,
/// The markers, at times in the composition.
pub markers: Vec<CMarker>,
}
/// One track of a composition.
#[derive(Clone, Debug, PartialEq)]
pub struct CTrack {
/// Whether the track carries picture or sound.
pub kind: CKind,
/// The name.
pub name: String,
/// Physical track number (1-based, per kind).
pub number: u32,
/// Sound: channels of the track (1 mono, 2 stereo, 6 5.1).
pub channels: u32,
/// The segments in order.
pub items: Vec<CItem>,
}
/// One segment of a track.
#[derive(Clone, Debug, PartialEq)]
pub enum CItem {
/// Nothing for the given length.
Filler(Tick),
/// A stretch of a source.
Clip(CClip),
/// A transition overlapping its neighbours.
Transition(CTransition),
}
@@ -75,30 +94,39 @@ impl CItem {
}
}
/// A clip: a stretch of one source on a track.
#[derive(Clone, Debug, PartialEq)]
pub struct CClip {
/// The length on the track.
pub len: Tick,
/// Index into [`Document::sources`].
pub source: usize,
/// Source (file) time of the segment's first frame.
pub start: Tick,
/// Sound: the clip gain, if any.
pub gain: Option<Gain>,
/// The name.
pub name: String,
}
/// Clip gain (linear amplitude).
#[derive(Clone, Debug, PartialEq)]
pub enum Gain {
/// One gain for the whole segment.
Constant(f64),
/// Points at offsets from the segment start; `linear` false = hold (step) interpolation.
Varying {
/// Whether the points join by straight lines rather than steps.
linear: bool,
/// The gain at each offset.
points: Vec<(Tick, f64)>,
},
}
/// A transition between the segments before and after it.
#[derive(Clone, Debug, PartialEq)]
pub struct CTransition {
/// The length on the track.
pub len: Tick,
/// Where the cut lies, from the transition start.
pub cut: Tick,
@@ -109,12 +137,18 @@ pub struct CTransition {
pub effect: String,
}
/// A marker or note at a time in a composition or source.
#[derive(Clone, Debug, PartialEq)]
pub struct CMarker {
/// Where it starts.
pub start: Tick,
/// How long it lasts; zero for a point.
pub duration: Tick,
/// The name.
pub name: String,
/// The free-text comment.
pub comment: String,
/// The colour name the writing application gave it.
pub color: Option<String>,
}
@@ -124,8 +158,11 @@ pub struct CMarker {
pub struct Source {
/// Groups the sources of one media item (one master mob).
pub key: String,
/// The name.
pub name: String,
/// Whether the essence is picture or sound.
pub kind: CKind,
/// The file the essence lives in; `None` for embedded data.
pub path: Option<String>,
/// Sound: the (0-based) channel of the file this source exposes (broken out to mono), or
/// `None` for all of them.
@@ -134,19 +171,27 @@ pub struct Source {
pub channels: u32,
/// Sound: channels of the file / embedded data.
pub file_channels: u32,
/// Picture: width in pixels.
pub width: u32,
/// Picture: height in pixels.
pub height: u32,
/// Picture: the frame rate of the media.
pub frame_rate: FrameRate,
/// Sound: samples per second.
pub sample_rate: u32,
/// Sound: bits per sample.
pub bits: u16,
/// The length of the essence.
pub length: Tick,
/// Media time of the essence's time 0 (trimmed / consolidated essence).
pub offset: Tick,
/// Start timecode in frames at `tc_rate`.
pub start_tc: Option<i64>,
/// The rate `start_tc` counts in.
pub tc_rate: FrameRate,
/// Essence data stored in the file itself.
pub embedded: Option<Vec<u8>>,
/// Markers on the source, at times in the essence.
pub markers: Vec<CMarker>,
/// Not media but a nested composition: its index in [`Document::nested`]. `start` of a clip
/// that uses it is a time in that composition.
+2 -2
View File
@@ -1,7 +1,7 @@
//! OMF Interchange 2.0 for audio post: written, and the same structures read.
//!
//! Written from the public *OMF Interchange Specification Version 2.0* (Avid Technology, 1995/97)
//! and Apple's *Bento Specification* revision 1.0d5 for the container ([`bento`]).
//! and Apple's *Bento Specification* revision 1.0d5 for the container.
//!
//! The file holds a composition mob (`CMOB`) with a timecode slot and one sound slot per audio
//! track (one per channel when broken out to mono): sequences (`SEQU`) of fillers (`FILL`), source
@@ -33,7 +33,7 @@ pub fn write(doc: &Document, identity: &Identity<'_>, report: &mut Report) -> Re
write::write(doc, identity, report)
}
/// Read an OMF 2.0 file (as written by [`write`] and by applications using the same structures).
/// Read an OMF 2.0 file (as written by [`fn@write`] and by applications using the same structures).
pub fn read(bytes: &[u8], report: &mut Report) -> Result<Document> {
read::read(bytes, report)
}
+10
View File
@@ -35,7 +35,9 @@
use std::collections::{BTreeMap, HashMap};
/// The eight-byte magic number that opens a Bento container.
pub const MAGIC: [u8; 8] = [0xA4, b'C', b'M', 0xA5, b'H', b'd', b'r', 0xD7];
/// The size in bytes of one label in the container table.
pub const LABEL_SIZE: usize = 24;
// standard object ids
@@ -97,6 +99,7 @@ impl Default for Writer {
}
impl Writer {
/// An empty writer that assigns user object ids from the first free id.
pub fn new() -> Writer {
Writer { data: Vec::new(), names: HashMap::new(), next: MIN_USER_ID, entries: Vec::new() }
}
@@ -114,14 +117,17 @@ impl Writer {
id
}
/// The id of the global property named `name`, assigned on first use.
pub fn property(&mut self, name: &str) -> u32 {
self.named(GLOBAL_PROP_NAME, name)
}
/// The id of the global type named `name`, assigned on first use.
pub fn type_id(&mut self, name: &str) -> u32 {
self.named(GLOBAL_TYPE_NAME, name)
}
/// Allocates the next free user object id.
pub fn new_object(&mut self) -> u32 {
let id = self.next;
self.next += 1;
@@ -156,6 +162,7 @@ impl Writer {
self.entries.push((obj, OBJ_REFERENCES, TYPE_7BIT_ASCII, vec![seg]));
}
/// Finishes the container and returns its bytes.
pub fn finish(mut self) -> Vec<u8> {
let seed = self.next;
self.entries.push((TOC_OBJECT, TOC_SEED, TOC_TYPE, vec![Seg::Imm(seed.to_be_bytes().to_vec())]));
@@ -245,6 +252,7 @@ impl<'a> Container<'a> {
self.objects.keys().copied()
}
/// Opens `data` as a Bento container, or says why it is not one.
pub fn open(data: &'a [u8]) -> Result<Container<'a>, String> {
if !sniff(data) {
return Err("no Bento label at the end of the file".into());
@@ -362,11 +370,13 @@ impl<'a> Container<'a> {
Ok(out)
}
/// The id registered for `name`, if any.
pub fn id_of(&self, name: &str) -> Option<u32> {
self.by_name.get(name).copied()
}
#[allow(dead_code)]
/// The name registered for `id`, if any.
pub fn name_of(&self, id: u32) -> Option<&str> {
self.names.get(&id).map(String::as_str)
}
+1 -1
View File
@@ -2,7 +2,7 @@
use std::collections::{HashMap, HashSet};
use craft_timeline::time::{FrameRate, Tick};
use craft_timeline::{FrameRate, Tick};
use super::bento::Container;
use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source, units_to_ticks};
+1 -1
View File
@@ -2,7 +2,7 @@
use std::collections::HashMap;
use craft_timeline::time::Tick;
use craft_timeline::Tick;
use super::bento;
use crate::model::{CItem, CKind, Document, Gain, Source, ticks_to_units};
+1 -1
View File
@@ -1,6 +1,6 @@
//! Documents written and read back, in both formats; damaged files.
use craft_timeline::time::{FrameRate, Tick};
use craft_timeline::{FrameRate, Tick};
use crate::model::{CItem, CKind, CMarker, Composition, Document, Gain};
use crate::testdoc::{IDENTITY, pcm_ramp, picture_and_sound, sound_only};
+1 -1
View File
@@ -1,7 +1,7 @@
//! Documents the tests write: what an editor's two-clip sequence with a dissolve looks like in
//! the model.
use craft_timeline::time::{FrameRate, Tick};
use craft_timeline::{FrameRate, Tick};
use crate::Identity;
use crate::model::{CClip, CItem, CKind, CTrack, CTransition, Composition, Document, Gain, Source};
+2 -2
View File
@@ -69,7 +69,7 @@ impl<'a> Entry<'a> {
/// An entry of an index whose bytes are still being written (the `.aepx` reader decodes into a
/// buffer that grows, so it keeps positions, not slices): the body is `start..start + len` of
/// that buffer. The fields are those of [`Entry`]; [`TreeIndex::from_drafts`] turns the list
/// that buffer. The fields are those of `Entry`; [`TreeIndex::from_drafts`] turns the list
/// into an index once the buffer is final.
#[derive(Debug, Clone, Copy)]
pub struct Draft {
@@ -140,7 +140,7 @@ impl<'a> TreeIndex<'a> {
/// The index of the entries `drafts` (in depth-first order, see [`Draft`]) whose bodies and
/// trailer are ranges of `buffer`. A range outside `buffer` reads as empty. The list is turned
/// into entries; a [`Draft`] and an [`Entry`] have the same size and alignment, so the standard
/// into entries; a [`Draft`] and an `Entry` have the same size and alignment, so the standard
/// library reuses the list's allocation for them.
pub fn from_drafts(buffer: &'a [u8], drafts: Vec<Draft>, trailer: (usize, usize)) -> Self {
let slice = |start: usize, len: usize| start.checked_add(len).and_then(|end| buffer.get(start..end)).unwrap_or(&[]);
+1 -1
View File
@@ -549,7 +549,7 @@ pub struct TextDocument {
/// run from the sampled defaults).
pub incomplete_runs: usize,
/// Style slots that are not decoded and differ from the sampled default (`"68"`, ...), each
/// once and at most [`MAX_UNDECODED_FIELDS`]; empty for every synthetic sample.
/// once and at most `MAX_UNDECODED_FIELDS`; empty for every synthetic sample.
pub undecoded_style_fields: Vec<String>,
/// Paragraph slots that are not decoded and differ from the sampled default.
pub undecoded_paragraph_fields: Vec<String>,
+1 -1
View File
@@ -453,7 +453,7 @@ pub struct KeyList<'f> {
}
/// What the property header says about its keyframe records: how many value components each
/// record holds and which of the two record templates applies (see [`KeyframeKind`]).
/// record holds and which of the two record templates applies (see `KeyframeKind`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyLayout {
/// `tdb4` byte 3.
+3 -3
View File
@@ -5,7 +5,7 @@ use std::io::Write;
use crate::chunk::{AepFile, Body, Chunk};
use crate::error::AepError;
/// Deepest tree [`write`] accepts (a hand-built tree may be deeper than any parsed one).
/// Deepest tree [`fn@write`] accepts (a hand-built tree may be deeper than any parsed one).
const MAX_WRITE_DEPTH: usize = 256;
/// Serialises `file`: `RIFX`, the recomputed container size, `Egg!`, the chunks and the trailer.
@@ -39,10 +39,10 @@ pub fn write(file: &AepFile<'_>) -> Result<Vec<u8>, AepError> {
Ok(out)
}
/// Like [`write`], into any writer.
/// Like [`fn@write`], into any writer.
///
/// # Errors
/// A size or depth error of [`write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors.
/// A size or depth error of [`fn@write`] becomes `ErrorKind::InvalidData`; otherwise I/O errors.
pub fn write_to(file: &AepFile<'_>, w: &mut impl Write) -> std::io::Result<()> {
let bytes = write(file).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
w.write_all(&bytes)
+8
View File
@@ -257,3 +257,11 @@ pub fn container(entries: &[(&str, &[u8], Method)], thumbnail_png: Option<&[u8]>
}
out
}
/// What `f` gives, and how many paragraph ends the reader looked up on this thread while it ran
/// to give each character run its paragraph's format.
pub fn count_paragraph_lookups<T>(f: impl FnOnce() -> T) -> (T, usize) {
crate::text::MATCH_READS.with(|reads| reads.set(0));
let value = f();
(value, crate::text::MATCH_READS.with(std::cell::Cell::get))
}
+28 -2
View File
@@ -240,12 +240,26 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
// Sorted by end (they are in order in every file), so both lookups below are binary
// searches: a block can have as many paragraphs and runs as characters.
paragraphs.sort_by_key(|(end, _)| *end);
let align_at = |i: usize| paragraphs.get(paragraphs.partition_point(|(end, _)| *end <= i)).map(|(_, a)| *a).or(open).unwrap_or_default();
let align_at = |i: usize| {
let at = paragraphs.partition_point(|(end, _)| {
count_match_read();
*end <= i
});
paragraphs.get(at).map(|(_, a)| *a).or(open).unwrap_or_default()
};
let mut cuts: Vec<usize> = paragraphs.iter().map(|(end, _)| *end).filter(|e| *e < chars.len()).collect();
cuts.dedup();
let push = |r: &mut Reader, runs: &mut Vec<TextRun>, attrs: Option<ObjId>, from: usize, to: usize, budget: &mut Option<usize>| {
// Split at paragraph ends so every run has one paragraph format.
let inside = cuts.get(cuts.partition_point(|c| *c <= from)..cuts.partition_point(|c| *c < to)).unwrap_or_default();
let first = cuts.partition_point(|c| {
count_match_read();
*c <= from
});
let past = cuts.partition_point(|c| {
count_match_read();
*c < to
});
let inside = cuts.get(first..past).unwrap_or_default();
let mut a = from;
for &c in inside.iter().chain(std::iter::once(&to)) {
push_run(r, runs, attrs, characters(&chars, a, c), world, budget, align_at(a));
@@ -282,6 +296,18 @@ pub(crate) fn story_runs(r: &mut Reader, story: ObjId, world: Affine) -> (Vec<Te
(runs, first_align.unwrap_or(Align::Left))
}
// Each paragraph end `story_runs` reads to match character runs to paragraphs, on this thread.
#[cfg(any(test, feature = "synth"))]
std::thread_local! {
pub(crate) static MATCH_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
#[inline]
fn count_match_read() {
#[cfg(any(test, feature = "synth"))]
MATCH_READS.with(|reads| reads.set(reads.get().saturating_add(1)));
}
fn characters(chars: &[char], start: usize, end: usize) -> String {
chars.get(start..end).unwrap_or_default().iter().filter(|c| **c != '\0' && **c != '\u{FFFC}').collect()
}
+26 -19
View File
@@ -111,25 +111,32 @@ fn a_shared_story_is_read_within_the_characters_of_one_document() {
#[test]
fn many_paragraphs_and_runs_are_matched_in_about_linear_time() {
// 200 000 paragraphs, each with its own run and format.
let n = 200_000;
let text = "a\u{2029}".repeat(n);
let fmt =
|end: usize| vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))];
let blk = F::Obj(
tag(b"StBl"),
vec![
(tag(b"Glyp"), utf8(&text)),
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
],
);
let started = std::time::Instant::now();
let d = open(vec![artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]))]);
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
assert_eq!(t.runs.len(), n);
// (About half a second; quadratic matching took over half a minute on the same machine.)
assert!(started.elapsed().as_secs() < 10, "{:?}", started.elapsed());
// `n` paragraphs, each with its own run and format, and how many paragraph ends matching
// them looks up.
let lookups = |n: usize| {
let text = "a\u{2029}".repeat(n);
let fmt = |end: usize| {
vec![(tag(b"Indx"), F::I32(end as i32)), (tag(b"Item"), F::Obj(tag(b"PAtt"), vec![(tag(b"Ints"), array_i32(b"Ints", &[1]))]))]
};
let blk = F::Obj(
tag(b"StBl"),
vec![
(tag(b"Glyp"), utf8(&text)),
(tag(b"GAtt"), F::Obj(tag(b"GlAS"), vec![(tag(b"Runs"), F::Objs(tag(b"GlAR"), (1..=n).map(|i| run(2 * i as i32, None)).collect()))])),
(tag(b"PAtt"), F::Obj(tag(b"PaAS"), vec![(tag(b"Runs"), F::Objs(tag(b"PaAR"), (1..=n).map(|i| fmt(2 * i)).collect()))])),
],
);
let story = artistic(F::Obj(tag(b"Stry"), vec![(tag(b"Blok"), F::Shared(vec![blk]))]));
let (d, lookups) = synth::count_paragraph_lookups(|| open(vec![story]));
let Kind::Text(t) = &d.spreads[0].nodes[0].kind else { panic!("text") };
assert_eq!(t.runs.len(), n);
lookups
};
// Four times the paragraphs and runs: a few binary searches each, so about four times the
// lookups (a little more for the longer searches), where matching each run against every
// paragraph is sixteen times.
let (quarter, full) = (lookups(50_000), lookups(200_000));
assert!(full <= 5 * quarter, "{quarter} lookups for 50,000 paragraphs, {full} for 200,000");
}
/// A shape node of `size` px.
+1
View File
@@ -1,4 +1,5 @@
[package]
autotests = false
name = "craft-ai-core"
description = "Shared data model for AI connections, roles, requests and jobs across the Craft apps"
version.workspace = true
+3 -47
View File
@@ -36,11 +36,13 @@ impl CapabilityId {
Ok(Self(s.to_owned()))
}
/// Builds an id from a modality and a task token. Fails when `task` is not a valid token.
pub fn new(modality: &Modality, task: &str) -> Result<Self, IdError> {
validate_token(task)?;
Ok(Self(format!("{}.{}", modality.as_str(), task)))
}
/// The full `modality.task` text.
pub fn as_str(&self) -> &str {
&self.0
}
@@ -51,6 +53,7 @@ impl CapabilityId {
Modality::parse(head).unwrap_or_else(|_| Modality::Other(head.to_owned()))
}
/// The task half, for example `inpaint` in `image.inpaint`.
pub fn task(&self) -> &str {
self.0.split_once('.').map_or("", |(_, t)| t)
}
@@ -117,50 +120,3 @@ pub const WELL_KNOWN: &[&str] = &[
pub fn well_known() -> Vec<CapabilityId> {
WELL_KNOWN.iter().filter_map(|s| CapabilityId::parse(s).ok()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn well_known_all_parse() {
assert_eq!(well_known().len(), WELL_KNOWN.len());
}
#[test]
fn splits_modality_and_task() {
let c = CapabilityId::parse("image.inpaint").unwrap();
assert_eq!(c.modality(), Modality::Image);
assert_eq!(c.task(), "inpaint");
}
#[test]
fn open_set_accepts_new_modalities() {
let c = CapabilityId::parse("cad.explain").unwrap();
assert_eq!(c.modality(), Modality::Other("cad".into()));
}
#[test]
fn rejects_malformed() {
for bad in ["", "image", "image.", ".inpaint", "image.in.paint", "im age.x", "image.in/paint"] {
assert!(CapabilityId::parse(bad).is_err(), "{bad:?} should be rejected");
}
}
#[test]
fn modality_round_trips_known_and_unknown() {
for text in ["image", "audio", "hologram"] {
let m = Modality::parse(text).unwrap();
assert_eq!(m.as_str(), text);
let back: Modality = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
assert_eq!(m, back);
}
}
#[test]
fn new_builds_from_parts() {
let c = CapabilityId::new(&Modality::Audio, "transcribe").unwrap();
assert_eq!(c.as_str(), "audio.transcribe");
assert!(CapabilityId::new(&Modality::Audio, "a.b").is_err());
}
}
+2
View File
@@ -16,7 +16,9 @@ pub const MAX_POLLS: u32 = 1000;
/// What a completed run produced.
#[derive(Debug)]
pub struct Completed {
/// The terminal state the job reached.
pub state: JobState,
/// Every event the polls reported, in order.
pub events: Vec<Event>,
}
+21 -85
View File
@@ -21,6 +21,7 @@ use crate::model::ModelInfo;
pub enum Locality {
/// Loopback server or in-process model: nothing leaves the machine.
Local,
/// The model runs on another machine. Consent applies.
Remote,
}
@@ -30,17 +31,22 @@ pub enum Locality {
pub enum Auth {
/// No credentials (a local model, an open local server).
None,
/// Authenticates with a stored key, sent in a header (see `Connection::key_header`).
ApiKey {
/// Locator of the key.
secret: SecretRef,
},
/// An official subscription route (for example the Codex app-server). `route` names it.
Subscription {
/// Name of the subscription route.
route: String,
/// Locator of the credential for the route.
secret: SecretRef,
},
}
impl Auth {
/// The secret locator this authentication uses, or `None` when it needs no credentials.
pub fn secret_ref(&self) -> Option<&SecretRef> {
match self {
Self::None => None,
@@ -53,28 +59,38 @@ impl Auth {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Billing {
/// No charge.
Free,
/// Pay per use, billed separately.
Metered,
/// Covered by an existing subscription's allowance.
SubscriptionAllowance,
/// The cost is not known.
Unknown,
}
/// A saved connection.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Connection {
#[allow(missing_docs)]
pub id: ConnectionId,
/// Name shown to the user.
pub label: String,
/// Which adapter talks to it, such as `http`, `openai`, `fal`, `comfyui`, `onnx`.
pub provider: String,
/// Server address, such as `https://host:port`. `None` for an in-process or route-only connection.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
/// Whether data stays on this machine. `validate` checks it against `endpoint`.
pub locality: Locality,
/// How the connection authenticates.
pub auth: Auth,
/// Who pays for use.
pub billing: Billing,
/// Models this connection offers. Ids must be unique.
#[serde(default)]
pub models: Vec<ModelInfo>,
/// When false, the connection is kept but not offered for use. Defaults to true.
#[serde(default = "yes")]
pub enabled: bool,
/// Header that carries the key, for a server that does not use `Authorization: Bearer`.
@@ -138,7 +154,9 @@ pub fn check_key_header(name: &str) -> Result<(), &'static str> {
/// Why a connection was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConnectionError {
/// The provider name is not a valid id.
Provider(IdError),
/// The endpoint cannot be parsed.
Endpoint(IdError),
/// Labelled `Local` but the endpoint is not loopback.
LocalButNotLoopback,
@@ -146,7 +164,9 @@ pub enum ConnectionError {
RemoteButLoopback,
/// No endpoint, labelled `Local`, yet it uses credentials. Such a route sends data away.
LocalWithoutEndpointNeedsNoAuth,
/// The label is empty or only whitespace.
EmptyLabel,
/// Two models share this id.
DuplicateModel(String),
/// A key header name that is not allowed, or a header named for a connection with no key.
KeyHeader(&'static str),
@@ -211,6 +231,7 @@ impl Connection {
Ok(())
}
/// The model with this id, if the connection lists it.
pub fn model(&self, id: &crate::ids::ModelId) -> Option<&ModelInfo> {
self.models.iter().find(|m| &m.id == id)
}
@@ -234,89 +255,4 @@ pub(crate) mod fixtures {
key_header: None,
}
}
pub fn local(id: &str) -> Connection {
Connection {
endpoint: Some("http://127.0.0.1:8188".into()),
locality: Locality::Local,
auth: Auth::None,
billing: Billing::Free,
..remote(id)
}
}
}
#[cfg(test)]
mod tests {
use super::fixtures::{local, remote};
use super::*;
#[test]
fn good_connections_validate() {
assert!(remote("a").validate().is_ok());
assert!(local("b").validate().is_ok());
}
#[test]
fn a_remote_host_cannot_be_labelled_local() {
let mut c = remote("a");
c.locality = Locality::Local;
assert_eq!(c.validate(), Err(ConnectionError::LocalButNotLoopback));
}
#[test]
fn the_userinfo_trick_cannot_make_a_remote_host_local() {
let mut c = local("a");
c.endpoint = Some("http://127.0.0.1@evil.example/".into());
assert!(matches!(c.validate(), Err(ConnectionError::Endpoint(_))));
}
#[test]
fn loopback_labelled_remote_is_flagged() {
let mut c = local("a");
c.locality = Locality::Remote;
assert_eq!(c.validate(), Err(ConnectionError::RemoteButLoopback));
}
#[test]
fn subscription_route_without_endpoint_cannot_be_local() {
let mut c = remote("codex");
c.endpoint = None;
c.auth = Auth::Subscription { route: "codex-app-server".into(), secret: SecretRef::new("s").unwrap() };
c.locality = Locality::Local;
assert_eq!(c.validate(), Err(ConnectionError::LocalWithoutEndpointNeedsNoAuth));
c.locality = Locality::Remote;
assert!(c.validate().is_ok());
}
#[test]
fn in_process_model_can_be_local_without_endpoint() {
let mut c = local("onnx");
c.endpoint = None;
assert!(c.validate().is_ok());
}
#[test]
fn duplicate_models_and_empty_labels_are_refused() {
let mut c = remote("a");
let m = ModelInfo::new(crate::ids::ModelId::new("m").unwrap(), "M");
c.models = vec![m.clone(), m];
assert!(matches!(c.validate(), Err(ConnectionError::DuplicateModel(_))));
let mut c = remote("b");
c.label = " ".into();
assert_eq!(c.validate(), Err(ConnectionError::EmptyLabel));
}
#[test]
fn serialized_form_holds_a_reference_not_a_secret() {
let json = serde_json::to_string(&remote("a")).unwrap();
assert!(json.contains("\"secret\":\"secret-a\""));
assert!(!json.to_lowercase().contains("sk-"));
}
#[test]
fn json_round_trip() {
let c = remote("a");
assert_eq!(serde_json::from_str::<Connection>(&serde_json::to_string(&c).unwrap()).unwrap(), c);
}
}
+14 -160
View File
@@ -24,27 +24,35 @@ use crate::request::Request;
/// One thing a request sends.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisclosureItem {
/// The role the input plays in the request.
pub role: InputRole,
/// The kind of data sent.
pub kind: PayloadKind,
/// Size in bytes when known.
pub bytes: Option<u64>,
}
/// What a request will send to a connection.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Disclosure {
/// The app that sends the request.
pub app: AppId,
/// The connection the request goes to.
pub connection: ConnectionId,
/// What the request asks the connection to do. Consent is given per capability.
pub capability: CapabilityId,
/// Whether the connection is local or remote.
pub locality: Locality,
/// `scheme://host[:port]`, or the route name when there is no endpoint.
pub destination: String,
/// The inputs the request sends.
pub items: Vec<DisclosureItem>,
/// Parameter names only, never values.
pub param_names: Vec<String>,
}
impl Disclosure {
/// Builds the disclosure for sending `request` from `app` through `connection`.
pub fn for_request(app: &AppId, connection: &Connection, request: &Request) -> Self {
let destination = connection
.endpoint
@@ -85,7 +93,9 @@ impl Disclosure {
/// another's.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConsentRecord {
/// The app that agreed.
pub app: AppId,
/// The connection agreed to.
pub connection: ConnectionId,
/// The destination agreed to. A different destination needs fresh consent.
pub destination: String,
@@ -93,6 +103,7 @@ pub struct ConsentRecord {
/// none and covers nothing, so the person is asked once more.
#[serde(default)]
pub capability: Option<CapabilityId>,
/// The kinds of data the agreement covers.
pub kinds: Vec<PayloadKind>,
/// Unix seconds. The agreement holds while the clock is before this; `None` holds until
/// revoked.
@@ -111,6 +122,7 @@ impl ConsentRecord {
/// An app's saved agreements.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConsentLedger {
/// The saved agreements.
#[serde(default)]
pub records: Vec<ConsentRecord>,
}
@@ -165,6 +177,7 @@ impl ConsentLedger {
}
}
/// Removes every agreement the app has for the connection, whatever the destination or capability.
pub fn revoke(&mut self, app: &AppId, connection: &ConnectionId) {
self.records.retain(|r| !(&r.app == app && &r.connection == connection));
}
@@ -174,7 +187,7 @@ impl ConsentLedger {
mod tests {
use super::*;
use crate::capability::CapabilityId;
use crate::connection::fixtures::{local, remote};
use crate::connection::fixtures::remote;
use crate::payload::Payload;
fn app() -> AppId {
@@ -188,32 +201,6 @@ mod tests {
.with_param("seed", 7.into())
}
#[test]
fn disclosure_lists_kinds_sizes_and_param_names_not_contents() {
let d = Disclosure::for_request(&app(), &remote("a"), &req());
assert_eq!(d.destination, "https://api.example.com");
assert_eq!(d.kinds(), vec![PayloadKind::Text, PayloadKind::Image]);
assert_eq!(d.items.first().and_then(|i| i.bytes), Some(10));
assert_eq!(d.param_names, vec!["seed".to_string()]);
let json = serde_json::to_string(&d).unwrap();
assert!(!json.contains("a cat"));
}
#[test]
fn local_connections_never_ask() {
let d = Disclosure::for_request(&app(), &local("a"), &req());
assert!(!ConsentLedger::default().needs_consent(&d, 0));
}
#[test]
fn remote_asks_until_granted_then_stops() {
let d = Disclosure::for_request(&app(), &remote("a"), &req());
let mut ledger = ConsentLedger::default();
assert!(ledger.needs_consent(&d, 0));
ledger.grant(&d);
assert!(!ledger.needs_consent(&d, 0));
}
#[test]
fn a_new_kind_of_data_asks_again() {
let mut ledger = ConsentLedger::default();
@@ -226,113 +213,10 @@ mod tests {
assert_eq!(ledger.records.len(), 1);
}
#[test]
fn changing_the_host_invalidates_consent() {
let mut ledger = ConsentLedger::default();
ledger.grant(&Disclosure::for_request(&app(), &remote("a"), &req()));
let mut moved = remote("a");
moved.endpoint = Some("https://other.example.org".into());
assert!(ledger.needs_consent(&Disclosure::for_request(&app(), &moved, &req()), 0));
}
#[test]
fn consent_is_per_app_and_revocable() {
let mut ledger = ConsentLedger::default();
let d = Disclosure::for_request(&app(), &remote("a"), &req());
ledger.grant(&d);
let other = Disclosure::for_request(&AppId::new("wordcraft").unwrap(), &remote("a"), &req());
assert!(ledger.needs_consent(&other, 0));
ledger.revoke(&app(), &remote("a").id);
assert!(ledger.needs_consent(&d, 0));
}
#[test]
fn parameters_alone_still_need_consent() {
let only_params = Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_param("negative", "a private note".into());
let d = disclosure_for(&only_params);
assert_eq!(d.kinds(), vec![PayloadKind::Text]);
let mut ledger = ConsentLedger::default();
assert!(ledger.needs_consent(&d, 0));
ledger.grant(&d);
assert!(!ledger.needs_consent(&d, 0));
}
fn upscale_req() -> Request {
Request::new(CapabilityId::parse("image.upscale").unwrap()).with_input(InputRole::Source, Payload::inline("image/png", vec![0; 10]).unwrap())
}
fn disclosure_for(r: &Request) -> Disclosure {
Disclosure::for_request(&app(), &remote("a"), r)
}
#[test]
fn disclosure_names_the_capability() {
assert_eq!(disclosure_for(&req()).capability, CapabilityId::parse("image.inpaint").unwrap());
}
#[test]
fn consent_for_one_capability_does_not_cover_another() {
let mut ledger = ConsentLedger::default();
ledger.grant(&disclosure_for(&req()));
let other = disclosure_for(&upscale_req());
assert!(ledger.needs_consent(&other, 0));
ledger.grant(&other);
assert!(!ledger.needs_consent(&other, 0));
assert!(!ledger.needs_consent(&disclosure_for(&req()), 0));
assert_eq!(ledger.records.len(), 2);
}
#[test]
fn a_timed_agreement_lapses_at_its_expiry() {
let d = disclosure_for(&req());
let mut ledger = ConsentLedger::default();
ledger.grant_until(&d, 1_000);
assert!(!ledger.needs_consent(&d, 0));
assert!(!ledger.needs_consent(&d, 999));
assert!(ledger.needs_consent(&d, 1_000));
assert!(ledger.needs_consent(&d, 5_000));
}
#[test]
fn an_open_agreement_never_lapses() {
let d = disclosure_for(&req());
let mut ledger = ConsentLedger::default();
ledger.grant(&d);
assert!(!ledger.needs_consent(&d, u64::MAX));
}
#[test]
fn agreeing_again_after_it_lapsed_renews_it() {
let d = disclosure_for(&req());
let mut ledger = ConsentLedger::default();
ledger.grant_until(&d, 1_000);
assert!(ledger.needs_consent(&d, 2_000));
ledger.grant_until(&d, 3_000);
assert!(!ledger.needs_consent(&d, 2_000));
assert!(ledger.needs_consent(&d, 3_000));
assert_eq!(ledger.records.len(), 1);
}
#[test]
fn the_latest_agreement_sets_the_expiry_for_that_capability() {
let d = disclosure_for(&req());
let mut ledger = ConsentLedger::default();
ledger.grant(&d);
ledger.grant_until(&d, 1_000);
assert!(ledger.needs_consent(&d, 1_000));
ledger.grant(&d);
assert!(!ledger.needs_consent(&d, u64::MAX));
}
#[test]
fn a_timed_agreement_for_one_capability_leaves_another_open() {
let mut ledger = ConsentLedger::default();
ledger.grant(&disclosure_for(&req()));
ledger.grant_until(&disclosure_for(&upscale_req()), 1_000);
assert!(!ledger.needs_consent(&disclosure_for(&req()), 5_000));
assert!(ledger.needs_consent(&disclosure_for(&upscale_req()), 5_000));
}
fn text_only_req() -> Request {
Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_input(InputRole::Prompt, Payload::text("a cat"))
}
@@ -347,34 +231,4 @@ mod tests {
assert!(!ledger.needs_consent(&text, 2_000));
assert!(ledger.needs_consent(&disclosure_for(&req()), 2_000), "image consent lapsed at 1000 and was not renewed");
}
#[test]
fn renewing_one_kind_leaves_the_others_on_their_own_expiry() {
let mut ledger = ConsentLedger::default();
ledger.grant_until(&disclosure_for(&req()), 1_000);
ledger.grant(&disclosure_for(&text_only_req()));
let both = disclosure_for(&req());
assert!(!ledger.needs_consent(&both, 999));
assert!(ledger.needs_consent(&both, 1_000));
assert!(!ledger.needs_consent(&disclosure_for(&text_only_req()), u64::MAX));
}
#[test]
fn a_record_from_before_scoping_loads_but_covers_nothing() {
let old = r#"{"records":[{"app":"photocraft","connection":"a","destination":"https://api.example.com","kinds":["text","image"]}]}"#;
let ledger: ConsentLedger = serde_json::from_str(old).unwrap();
assert_eq!(ledger.records.len(), 1);
assert_eq!(ledger.records[0].capability, None);
assert_eq!(ledger.records[0].expires_at, None);
assert!(ledger.needs_consent(&disclosure_for(&req()), 0));
}
#[test]
fn the_capability_and_expiry_survive_a_save() {
let mut ledger = ConsentLedger::default();
ledger.grant_until(&disclosure_for(&req()), 1_000);
let back: ConsentLedger = serde_json::from_str(&serde_json::to_string(&ledger).unwrap()).unwrap();
assert_eq!(back, ledger);
assert_eq!(back.records[0].expires_at, Some(1_000));
}
}
+20 -2
View File
@@ -40,10 +40,13 @@ pub struct Preset {
pub key: &'static str,
/// What the button says.
pub name: &'static str,
/// Adapter name the preset selects.
pub provider: &'static str,
/// Empty for "type your own".
pub endpoint: &'static str,
/// Billing the preset assumes.
pub billing: Billing,
/// Whether the form asks for a key.
pub needs_key: bool,
/// One line about it, shown under the name.
pub note: &'static str,
@@ -182,9 +185,13 @@ fn preset_models(preset: &Preset) -> Vec<ModelInfo> {
/// Which box a problem belongs to, so a form can mark it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Field {
#[allow(missing_docs)]
Label,
#[allow(missing_docs)]
Provider,
#[allow(missing_docs)]
Address,
#[allow(missing_docs)]
Key,
/// The name of the header that carries the key.
KeyHeader,
@@ -193,7 +200,9 @@ pub enum Field {
/// Why a draft was refused. The message is safe to show.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DraftError {
/// The box the problem belongs to.
pub field: Field,
/// What to tell the user.
pub message: String,
}
@@ -216,6 +225,7 @@ impl std::error::Error for DraftError {}
pub enum KeyChange {
/// Leave whatever is saved.
Keep,
/// Save this key, replacing any saved one.
Set(SecretString),
/// The connection no longer uses a key; remove the saved one.
Clear,
@@ -224,7 +234,9 @@ pub enum KeyChange {
/// A checked connection and what to do with its key.
#[derive(Clone, Debug)]
pub struct Prepared {
/// The validated connection to save.
pub connection: Connection,
/// What to do with the stored key.
pub key: KeyChange,
}
@@ -233,17 +245,23 @@ pub struct Prepared {
pub struct ConnectionDraft {
/// `Some` when editing an existing connection.
pub editing: Option<ConnectionId>,
#[allow(missing_docs)]
pub label: String,
#[allow(missing_docs)]
pub provider: String,
#[allow(missing_docs)]
pub endpoint: String,
#[allow(missing_docs)]
pub billing: Billing,
/// Whether the connection authenticates with a key.
pub uses_key: bool,
/// Text typed into the key box. Empty while editing means "keep the saved key". It is a plain
/// string only because a text box needs one; [`Debug`] never prints it and [`prepare`]
/// string only because a text box needs one; [`Debug`] never prints it and [`Self::prepare`]
/// (Self::prepare) turns it into a [`SecretString`].
pub key: String,
/// Header that carries the key; empty sends it as `Authorization: Bearer`.
pub key_header: String,
/// Whether the connection is offered for use.
pub enabled: bool,
/// Models carried onto the saved connection. Assigning here declares them by hand and records
/// no address, so they survive any address change; models a test found go through
@@ -329,7 +347,7 @@ impl ConnectionDraft {
/// A test is not instant and the address stays editable while it runs, so its answer can
/// arrive after the address has changed, or after a later test at the new address has already
/// answered. Recording it then would file one endpoint's models under another, which is what
/// [`models_fit`](Self::models_fit) exists to prevent. An answer is therefore taken only while
/// `models_fit` exists to prevent. An answer is therefore taken only while
/// the field still holds the address it was asked of, and a late one is dropped. Returns
/// whether the models were taken, so a caller can say "this result is out of date".
///
-228
View File
@@ -10,120 +10,6 @@ fn with_key(mut d: ConnectionDraft, key: &str) -> ConnectionDraft {
d
}
#[test]
fn every_preset_with_an_address_makes_a_valid_connection() {
for p in PRESETS.iter().filter(|p| !p.endpoint.is_empty()) {
let d = with_key(ConnectionDraft::from_preset(p), "sk-test-123");
let prepared = d.prepare(&[]).unwrap_or_else(|e| panic!("{}: {e}", p.key));
assert!(prepared.connection.validate().is_ok());
assert_eq!(prepared.connection.auth.secret_ref().is_some(), p.needs_key, "{}", p.key);
}
// The custom preset needs an address typed in.
let custom = with_key(draft("custom"), "k");
assert_eq!(custom.prepare(&[]).unwrap_err().field, Field::Address);
}
#[test]
fn artcraft_api_key_preset_is_distinct_from_unverified_account_access() {
let p = PRESETS.iter().find(|p| p.key == "artcraft-omni").unwrap();
assert_eq!(p.provider, "artcraft-omni");
assert!(p.needs_key);
assert_eq!(p.endpoint, "https://api.storyteller.ai");
assert!(!PRESETS.iter().any(|p| p.key == "artcraft-account"));
let prepared = with_key(ConnectionDraft::from_preset(p), "test-key").prepare(&[]).unwrap();
assert_eq!(prepared.connection.models.len(), 2);
assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "nano_banana"));
assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "seedance_2p0"));
}
#[test]
fn where_it_goes_decides_local_or_remote() {
assert_eq!(draft("ollama").locality(), Some(Locality::Local));
assert_eq!(draft("openai").locality(), Some(Locality::Remote));
let mut d = draft("custom");
assert_eq!(d.locality(), None, "no address yet");
d.endpoint = "https://localhost.evil.example".into();
assert_eq!(d.locality(), Some(Locality::Remote), "a lookalike host is remote");
d.endpoint = "not a url".into();
assert_eq!(d.locality(), None);
// The connection carries what the address says, whatever the preset hoped.
let mut o = with_key(draft("ollama"), "");
o.endpoint = "https://api.example.com/v1".into();
let c = o.prepare(&[]).unwrap().connection;
assert_eq!(c.locality, Locality::Remote);
}
#[test]
fn plain_http_is_refused_unless_it_is_this_computer() {
let mut d = with_key(draft("custom"), "k");
d.endpoint = "http://192.168.1.20:8000/v1".into();
let e = d.prepare(&[]).unwrap_err();
assert_eq!(e.field, Field::Address);
assert!(e.message.contains("https://"), "{e}");
d.endpoint = "http://user:pw@127.0.0.1/v1".into();
assert!(d.prepare(&[]).is_err());
}
#[test]
fn keys_must_be_one_clean_line() {
for bad in ["sk-abc\ndef", "sk abc", "sk-\u{e9}", "sk-abc\u{0}", &"x".repeat(MAX_KEY_BYTES + 1)] {
let d = with_key(draft("openai"), bad);
let e = d.prepare(&[]).unwrap_err();
assert_eq!(e.field, Field::Key, "{bad:?}");
assert!(!e.message.contains("abc"), "the message must not echo the key");
}
// Surrounding whitespace from a paste is trimmed, not refused.
let d = with_key(draft("openai"), " sk-good-key\r\n");
match d.prepare(&[]).unwrap().key {
KeyChange::Set(k) => assert_eq!(k.expose(), "sk-good-key"),
other => panic!("{other:?}"),
}
}
#[test]
fn a_new_connection_that_needs_a_key_must_have_one() {
let e = draft("openai").prepare(&[]).unwrap_err();
assert_eq!(e.field, Field::Key);
// Turning the key off makes it a no-key connection.
let mut d = draft("openai");
d.uses_key = false;
let p = d.prepare(&[]).unwrap();
assert_eq!(p.connection.auth, Auth::None);
assert!(matches!(p.key, KeyChange::Keep), "nothing saved, nothing to clear");
}
#[test]
fn names_are_checked() {
let mut d = with_key(draft("openai"), "k");
d.label = " ".into();
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
d.label = "two\nlines".into();
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
d.label = "x".repeat(MAX_LABEL_CHARS + 1);
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
d.label = "OpenAI".into();
d.provider = "bad provider!".into();
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Provider);
}
#[test]
fn ids_come_from_the_name_and_stay_unique() {
let first = with_key(draft("openai"), "k").prepare(&[]).unwrap();
assert_eq!(first.connection.id.as_str(), "openai");
assert_eq!(first.connection.auth.secret_ref().unwrap().as_str(), "openai.key");
let second = with_key(draft("openai"), "k2").prepare(std::slice::from_ref(&first.connection)).unwrap();
assert_eq!(second.connection.id.as_str(), "openai-2");
// Two connections never share a key, even with the same name.
assert_eq!(second.connection.auth.secret_ref().unwrap().as_str(), "openai-2.key");
let mut odd = with_key(draft("openai"), "k");
odd.label = "!!! Café Ünïcode ???".into();
let c = odd.prepare(&[]).unwrap().connection;
assert_eq!(c.id.as_str(), "caf-n-code");
odd.label = "???".into();
assert_eq!(odd.prepare(&[]).unwrap().connection.id.as_str(), "connection");
assert_eq!(c.label, "!!! Café Ünïcode ???", "the label itself is kept as typed");
}
#[test]
fn a_taken_key_locator_is_never_reused() {
let mut other = with_key(draft("openai"), "k").prepare(&[]).unwrap().connection;
@@ -133,117 +19,3 @@ fn a_taken_key_locator_is_never_reused() {
let p = with_key(draft("openai"), "k2").prepare(&[other]).unwrap();
assert_eq!(p.connection.auth.secret_ref().unwrap().as_str(), "openai.key2");
}
fn saved_openai() -> Connection {
let mut c = with_key(draft("openai"), "sk-x").prepare(&[]).unwrap().connection;
c.models = vec![ModelInfo::new(crate::ids::ModelId::new("gpt-x").unwrap(), "GPT X")];
c
}
#[test]
fn editing_keeps_the_saved_key_unless_a_new_one_is_typed() {
let saved = saved_openai();
let mut d = ConnectionDraft::from_connection(&saved);
assert!(d.key.is_empty());
d.label = "Work OpenAI".into();
let p = d.prepare(std::slice::from_ref(&saved)).unwrap();
assert!(matches!(p.key, KeyChange::Keep));
assert_eq!(p.connection.id, saved.id, "the id never changes on rename");
assert_eq!(p.connection.auth, saved.auth, "same secret locator");
d.key = "sk-new".into();
assert!(matches!(d.prepare(std::slice::from_ref(&saved)).unwrap().key, KeyChange::Set(_)));
}
#[test]
fn turning_the_key_off_clears_the_saved_one() {
let saved = saved_openai();
let mut d = ConnectionDraft::from_connection(&saved);
d.uses_key = false;
let p = d.prepare(std::slice::from_ref(&saved)).unwrap();
assert!(matches!(p.key, KeyChange::Clear));
assert_eq!(p.connection.auth, Auth::None);
}
#[test]
fn models_follow_the_address() {
let saved = saved_openai();
let same = ConnectionDraft::from_connection(&saved);
assert_eq!(same.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.len(), 1);
let mut moved = ConnectionDraft::from_connection(&saved);
moved.endpoint = "https://other.example.com/v1".into();
assert!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
}
#[test]
fn models_found_at_the_new_address_are_kept() {
let saved = saved_openai();
let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")];
let mut moved = ConnectionDraft::from_connection(&saved);
moved.endpoint = "https://other.example.com/v1".into();
assert!(moved.set_models("https://other.example.com/v1", found.clone()));
assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, found);
}
#[test]
fn a_retest_that_finds_the_same_models_keeps_them() {
let saved = saved_openai();
let mut moved = ConnectionDraft::from_connection(&saved);
moved.endpoint = "https://other.example.com/v1".into();
assert!(moved.set_models("https://other.example.com/v1", saved.models.clone()));
assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models);
}
#[test]
fn models_found_before_the_address_changed_are_dropped() {
let saved = saved_openai();
let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")];
let mut d = ConnectionDraft::from_connection(&saved);
let at = d.endpoint.clone();
assert!(d.set_models(&at, found));
d.endpoint = "https://other.example.com/v1".into();
assert!(d.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
}
#[test]
fn editing_something_removed_elsewhere_is_an_error() {
let saved = saved_openai();
let d = ConnectionDraft::from_connection(&saved);
assert!(d.prepare(&[]).is_err());
}
#[test]
fn nothing_secret_shows_in_debug_or_errors() {
let d = with_key(draft("openai"), "sk-very-secret-value");
assert!(!format!("{d:?}").contains("secret-value"));
let mut bad = d.clone();
bad.endpoint = "nope".into();
let e = bad.prepare(&[]).unwrap_err();
assert!(!format!("{e} {e:?}").contains("secret-value"));
let p = d.prepare(&[]).unwrap();
assert!(!format!("{p:?}").contains("secret-value"));
}
#[test]
fn hostile_text_never_panics() {
let nasty = ["", "\0", "\u{202e}rtl", "💥💥💥", &"a".repeat(100_000), "http://[::1", "https://", "%00%00", "' OR 1=1 --"];
for a in nasty {
for b in nasty {
let mut d = draft("custom");
d.label = a.to_owned();
d.endpoint = b.to_owned();
d.provider = a.to_owned();
d.key = b.to_owned();
let _ = d.prepare(&[]);
let _ = d.locality();
}
}
}
#[test]
fn seedance_connects_through_byteplus_modelark_with_an_api_key() {
let p = PRESETS.iter().find(|p| p.key == "seedance").unwrap();
assert_eq!(p.endpoint, "https://ark.ap-southeast.bytepluses.com/api/v3");
assert!(p.name.contains("BytePlus"), "{}", p.name);
assert!(!p.name.contains("Volcengine"), "{}", p.name);
assert!(p.needs_key);
}
+3 -48
View File
@@ -15,8 +15,11 @@ const MAX_ENDPOINT_LEN: usize = 2048;
/// A parsed endpoint.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Endpoint {
/// True for `https`, false for `http`.
pub https: bool,
/// Host name or address, without port.
pub host: String,
/// Explicit port, or `None` for the scheme default.
pub port: Option<u16>,
}
@@ -100,26 +103,6 @@ fn parse_port(p: &str) -> Result<u16, IdError> {
mod tests {
use super::*;
#[test]
fn loopback_forms() {
for ok in ["http://localhost:8188", "http://127.0.0.1:11434/v1", "http://127.9.9.9", "http://[::1]:8080/x"] {
assert!(Endpoint::parse(ok).unwrap().is_loopback(), "{ok}");
}
}
#[test]
fn remote_https() {
let e = Endpoint::parse("https://api.example.com/v1").unwrap();
assert!(!e.is_loopback());
assert_eq!(e.fingerprint(), "https://api.example.com");
}
#[test]
fn plain_http_to_a_remote_host_is_refused() {
assert!(Endpoint::parse("http://api.example.com").is_err());
assert!(Endpoint::parse("http://192.168.1.20:8188").is_err());
}
#[test]
fn userinfo_trick_is_refused() {
assert!(Endpoint::parse("http://127.0.0.1@evil.example/").is_err());
@@ -135,32 +118,4 @@ mod tests {
assert!(!Endpoint::parse(host).unwrap().is_loopback(), "{host}");
}
}
#[test]
fn rejects_garbage_without_panicking() {
for bad in [
"",
"ftp://x",
"https://",
"https://:80",
"http://[::1",
"http://[::1]x",
"https://a b",
"https://a:99999",
"https://a\\b",
"localhost:8080",
] {
assert!(Endpoint::parse(bad).is_err(), "{bad:?}");
}
assert!(Endpoint::parse(&format!("https://{}", "a".repeat(5000))).is_err());
}
#[test]
fn fingerprint_changes_with_host_and_port() {
let a = Endpoint::parse("https://a.example:8443/x").unwrap().fingerprint();
let b = Endpoint::parse("https://b.example:8443/x").unwrap().fingerprint();
assert_eq!(a, "https://a.example:8443");
assert_ne!(a, b);
assert_eq!(Endpoint::parse("http://[::1]:80").unwrap().fingerprint(), "http://[::1]:80");
}
}
+9 -35
View File
@@ -38,6 +38,7 @@ pub enum ErrorKind {
}
impl ErrorKind {
/// A short lowercase name for messages and logs.
pub fn as_str(self) -> &'static str {
match self {
Self::Unsupported => "unsupported",
@@ -57,25 +58,32 @@ impl ErrorKind {
/// The error type of the whole crate.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AiError {
/// What went wrong, for the app to act on.
pub kind: ErrorKind,
/// Human-readable detail. Secrets are scrubbed when built with [`AiError::redacted`].
pub message: String,
/// How long to wait before retrying, when the provider said so.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retry_after_secs: Option<u64>,
}
impl AiError {
/// Builds an error of the given kind.
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self { kind, message: message.into(), retry_after_secs: None }
}
/// Builds an [`ErrorKind::Unsupported`] error.
pub fn unsupported(message: impl Into<String>) -> Self {
Self::new(ErrorKind::Unsupported, message)
}
/// Builds an [`ErrorKind::InvalidRequest`] error.
pub fn invalid(message: impl Into<String>) -> Self {
Self::new(ErrorKind::InvalidRequest, message)
}
/// Builds an [`ErrorKind::Cancelled`] error.
pub fn cancelled() -> Self {
Self::new(ErrorKind::Cancelled, "cancelled")
}
@@ -85,6 +93,7 @@ impl AiError {
Self::new(kind, redact(message, secrets))
}
/// Sets the wait, in seconds, before a retry.
pub fn with_retry_after(mut self, secs: u64) -> Self {
self.retry_after_secs = Some(secs);
self
@@ -103,38 +112,3 @@ impl fmt::Display for AiError {
}
impl std::error::Error for AiError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn redacted_removes_the_key() {
let key = SecretString::new("sk-test-999");
let e = AiError::redacted(ErrorKind::Auth, "invalid key sk-test-999", &[&key]);
assert!(!e.message.contains("999"));
assert!(!format!("{e}").contains("999"));
}
#[test]
fn consent_required_is_not_retryable_and_round_trips() {
let e = AiError::new(ErrorKind::ConsentRequired, "ask first");
assert!(!e.is_retryable());
let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(back.kind, ErrorKind::ConsentRequired);
assert!(format!("{e}").starts_with("consent required"));
}
#[test]
fn retryable_kinds() {
assert!(AiError::new(ErrorKind::RateLimited, "x").is_retryable());
assert!(!AiError::unsupported("x").is_retryable());
}
#[test]
fn round_trips_through_json() {
let e = AiError::new(ErrorKind::RateLimited, "slow down").with_retry_after(30);
let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(e, back);
}
}
+26 -4
View File
@@ -28,27 +28,41 @@ pub const MAX_PROMPT_CHARS: usize = 2000;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum Outcome {
/// The job finished and produced a result.
Done,
Failed { kind: ErrorKind },
/// The job failed. Only the error kind is kept, never the message.
Failed {
/// What kind of failure it was.
kind: ErrorKind,
},
/// The user or app cancelled the job.
Cancelled,
}
/// Written when a job is submitted (or refused by the provider).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StartRecord {
/// Schema version, [`HISTORY_SCHEMA`].
pub v: u32,
/// Joins this line to its [`EndRecord`]. Unique across apps and runs.
pub run: String,
/// Unix milliseconds.
pub at_ms: u64,
/// Id of the app that submitted the job.
pub app: String,
/// Id of the role the job ran for.
pub role_id: String,
/// The feature as the user knows it, such as "Generative Fill".
pub role_label: String,
/// The capability requested, as `<modality>.<task>`.
pub capability: String,
/// Id of the connection used.
pub connection: String,
/// The connection's label when the job ran, kept in case the connection is later renamed or removed.
pub connection_label: String,
/// Id of the model used.
pub model: String,
/// Whether the connection was local or remote.
pub locality: Locality,
/// `scheme://host[:port]`, or the route name when there is no endpoint.
pub destination: String,
@@ -73,9 +87,13 @@ pub struct StartRecord {
/// Written when a job reaches a final state.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EndRecord {
/// Schema version, [`HISTORY_SCHEMA`].
pub v: u32,
/// The run id shared with the [`StartRecord`].
pub run: String,
/// Unix milliseconds when the job ended.
pub at_ms: u64,
/// How the job ended.
pub outcome: Outcome,
/// What the provider reported, or `None`. Never an estimate of ours.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -88,14 +106,18 @@ pub struct EndRecord {
#[serde(tag = "phase", rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum HistoryRecord {
/// The line written at submission.
Start(StartRecord),
/// The line written at the final state.
End(EndRecord),
}
/// A job as the history list shows it: the start line and, if seen, the end line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HistoryEntry {
/// The submission line.
pub start: StartRecord,
/// The final line, or `None` while unfinished.
pub end: Option<EndRecord>,
}
@@ -106,6 +128,7 @@ impl HistoryEntry {
end.at_ms.checked_sub(self.start.at_ms)
}
/// How the job ended, or `None` while unfinished.
pub fn outcome(&self) -> Option<&Outcome> {
self.end.as_ref().map(|e| &e.outcome)
}
@@ -120,7 +143,9 @@ impl HistoryEntry {
/// Entries newest first, plus how many lines could not be read.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HistoryLog {
/// Jobs, newest first.
pub entries: Vec<HistoryEntry>,
/// Lines that could not be read and were left out.
pub skipped: usize,
}
@@ -161,6 +186,3 @@ pub fn clip_prompt(text: &str) -> String {
}
pub mod report;
#[cfg(test)]
mod tests;
+16
View File
@@ -16,8 +16,11 @@ const DAY_MS: i64 = 86_400_000;
/// A calendar day.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Day {
#[allow(missing_docs)]
pub year: i32,
/// Month number, 1 to 12.
pub month: u8,
/// Day of the month, starting at 1.
pub day: u8,
}
@@ -38,6 +41,7 @@ impl Day {
civil_from_days(days)
}
/// The month this day falls in.
pub fn month(self) -> Month {
Month { year: self.year, month: self.month }
}
@@ -52,7 +56,9 @@ impl fmt::Display for Day {
/// A calendar month.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Month {
#[allow(missing_docs)]
pub year: i32,
/// Month number, 1 to 12.
pub month: u8,
}
@@ -128,19 +134,23 @@ fn exact_amount(micros: u64) -> String {
/// Which entries to show. An empty filter shows everything.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct HistoryFilter {
/// Only jobs from this app id.
pub app: Option<String>,
/// Only jobs that used this model id.
pub model: Option<String>,
/// Only jobs that started at or after this Unix-millisecond time.
pub since_ms: Option<u64>,
}
impl HistoryFilter {
/// Whether `entry` passes every filter that is set.
pub fn matches(&self, entry: &HistoryEntry) -> bool {
self.app.as_ref().is_none_or(|a| *a == entry.start.app)
&& self.model.as_ref().is_none_or(|m| *m == entry.start.model)
&& self.since_ms.is_none_or(|t| entry.start.at_ms >= t)
}
/// The entries that pass, in their original order.
pub fn apply<'a>(&self, entries: &'a [HistoryEntry]) -> Vec<&'a HistoryEntry> {
entries.iter().filter(|e| self.matches(e)).collect()
}
@@ -164,9 +174,13 @@ fn distinct<'a>(items: impl Iterator<Item = &'a str>) -> Vec<String> {
/// A count of jobs and the money the providers reported for them.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Totals {
/// Every job counted, finished or not.
pub jobs: usize,
/// Jobs that finished successfully.
pub done: usize,
/// Jobs that failed.
pub failed: usize,
/// Jobs that were cancelled.
pub cancelled: usize,
/// Started, but the app closed before the end was seen.
pub unfinished: usize,
@@ -181,6 +195,7 @@ pub struct Totals {
}
impl Totals {
/// Counts one entry into the totals.
pub fn add(&mut self, entry: &HistoryEntry) {
self.jobs += 1;
if matches!(entry.outcome(), Some(Outcome::Done))
@@ -213,6 +228,7 @@ impl Totals {
}
}
/// Sums `entries` into one [`Totals`].
pub fn totals<'a>(entries: impl IntoIterator<Item = &'a HistoryEntry>) -> Totals {
let mut t = Totals::default();
for e in entries {
+1 -168
View File
@@ -1,10 +1,8 @@
use super::*;
use crate::connection::Locality;
use crate::error::ErrorKind;
use crate::history::{EndRecord, HISTORY_SCHEMA, HistoryRecord, StartRecord, merge};
use crate::job::{CostEstimate, Usage};
use crate::job::Usage;
const HOUR: u64 = 3_600_000;
const T0: u64 = 1_760_000_000_000; // 2025-10-09T08:53:20Z
fn start(run: &str, at_ms: u64, app: &str, model: &str) -> StartRecord {
@@ -63,112 +61,6 @@ fn days_are_right_across_leap_days_epoch_and_year_ends() {
assert_eq!(day_of(T0, 0).to_string(), "2025-10-09");
}
#[test]
fn the_offset_moves_the_day_boundary_both_ways() {
let late = 1_767_225_599_000; // 2025-12-31T23:59:59Z
assert_eq!(day_of(late, 60).to_string(), "2026-01-01");
assert_eq!(day_of(late, -300).to_string(), "2025-12-31");
let early = 1_767_225_600_000; // 2026-01-01T00:00:00Z
assert_eq!(day_of(early, -1).to_string(), "2025-12-31");
assert_eq!(day_of(0, -60).to_string(), "1969-12-31");
}
#[test]
fn iso_time_is_utc_and_padded() {
assert_eq!(iso_utc(T0), "2025-10-09T08:53:20Z");
assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");
}
#[test]
fn amounts_are_exact_and_small_costs_are_not_zero() {
assert_eq!(amount_text(31_000), "0.03");
assert_eq!(amount_text(1_234_567), "1.23");
assert_eq!(amount_text(1_500), "0.0015");
assert_eq!(amount_text(0), "0.0000");
assert_eq!(exact_amount(31_000), "0.031000");
assert_eq!(exact_amount(2_000_001), "2.000001");
}
#[test]
fn the_filter_narrows_by_app_model_and_time_and_empty_shows_all() {
let e = entries(&[
("a", T0, "photocraft", "m1", Some(Outcome::Done), Some(1)),
("b", T0 + HOUR, "wordcraft", "m1", Some(Outcome::Done), None),
("c", T0 + 2 * HOUR, "photocraft", "m2", None, None),
]);
assert_eq!(HistoryFilter::default().apply(&e).len(), 3);
let photo = HistoryFilter { app: Some("photocraft".into()), ..HistoryFilter::default() };
assert_eq!(photo.apply(&e).len(), 2);
let both = HistoryFilter { model: Some("m2".into()), ..photo.clone() };
assert_eq!(both.apply(&e).len(), 1);
let recent = HistoryFilter { since_ms: Some(T0 + HOUR), ..HistoryFilter::default() };
let runs: Vec<_> = recent.apply(&e).iter().map(|x| x.start.run.clone()).collect();
assert_eq!(runs, ["c", "b"], "inclusive of the boundary, newest first");
assert_eq!(apps(&e), ["photocraft", "wordcraft"]);
assert_eq!(models(&e), ["m1", "m2"]);
}
#[test]
fn totals_count_outcomes_and_sum_cost_per_currency() {
let e = entries(&[
("a", T0, "p", "m", Some(Outcome::Done), Some(40_000)),
("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(25_000)),
("c", T0 + 2, "p", "m", Some(Outcome::Done), None),
("d", T0 + 3, "p", "m", Some(Outcome::Failed { kind: ErrorKind::Quota }), None),
("e", T0 + 4, "p", "m", Some(Outcome::Cancelled), None),
("f", T0 + 5, "p", "m", None, None),
]);
let t = totals(&e);
assert_eq!(t.jobs, 6);
assert_eq!((t.done, t.failed, t.cancelled, t.unfinished), (3, 1, 1, 1));
assert_eq!(t.cost_micros.get("USD"), Some(&65_000));
assert_eq!(t.without_cost, 1, "only a finished success counts as unpriced");
}
#[test]
fn a_huge_cost_saturates_instead_of_wrapping() {
let e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(u64::MAX)), ("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(10))]);
assert_eq!(totals(&e).cost_micros.get("USD"), Some(&u64::MAX));
}
#[test]
fn days_and_months_group_newest_first() {
let day = 24 * HOUR;
let e = entries(&[
("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)),
("b", T0 + HOUR, "p", "m", Some(Outcome::Done), Some(20_000)),
("c", T0 + day, "p", "m", Some(Outcome::Done), Some(5_000)),
("d", T0 + 30 * day, "p", "m", Some(Outcome::Done), Some(1_000)),
]);
let refs: Vec<&HistoryEntry> = e.iter().collect();
let days = by_day(&refs, 0);
let labels: Vec<_> = days.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect();
assert_eq!(labels, [("2025-11-08".to_owned(), 1), ("2025-10-10".to_owned(), 1), ("2025-10-09".to_owned(), 2)]);
let months = by_month(&refs, 0);
let labels: Vec<_> = months.iter().map(|(m, t)| (m.to_string(), t.jobs, t.cost_micros.get("USD").copied())).collect();
assert_eq!(labels, [("2025-11".to_owned(), 1, Some(1_000)), ("2025-10".to_owned(), 3, Some(35_000))]);
}
#[test]
fn csv_has_a_header_one_row_per_entry_and_matching_column_counts() {
let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(31_000)), ("b", T0 + 5, "p", "m", None, None)]);
e[0].start.estimate = Some(CostEstimate { micros: 30_000, currency: "USD".into(), billing: crate::Billing::Metered });
let refs: Vec<&HistoryEntry> = e.iter().collect();
let csv = to_csv(&refs);
let lines: Vec<&str> = csv.split("\r\n").collect();
assert_eq!(lines.len(), 4, "header, two rows, trailing empty");
assert!(lines[0].starts_with("started_utc,app,feature"));
assert_eq!(lines[0].split(',').count(), CSV_HEADER.len());
// Newest first: the unfinished job (b) is the first row.
assert!(lines[1].contains(",unfinished,"), "{}", lines[1]);
assert!(lines[1].contains("0.030000,USD"), "estimate: {}", lines[1]);
assert!(lines[2].contains("0.031000,USD"), "{}", lines[2]);
assert!(lines[2].contains(",done,"), "{}", lines[2]);
assert!(lines[2].contains(",2.000,"), "two seconds: {}", lines[2]);
assert_eq!(lines[1].split(',').count(), CSV_HEADER.len());
assert_eq!(lines[2].split(',').count(), CSV_HEADER.len());
}
#[test]
fn csv_quotes_awkward_text_and_defuses_formulas() {
let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), None)]);
@@ -183,27 +75,6 @@ fn csv_quotes_awkward_text_and_defuses_formulas() {
assert!(!csv.contains(",=HYPERLINK"), "{csv}");
}
#[test]
fn a_failed_job_exports_its_error_kind() {
let e = entries(&[("a", T0, "p", "m", Some(Outcome::Failed { kind: ErrorKind::RateLimited }), None)]);
let refs: Vec<&HistoryEntry> = e.iter().collect();
assert!(to_csv(&refs).contains(",failed,rate_limited,"));
}
#[test]
fn list_times_and_day_starts_follow_the_offset() {
assert_eq!(time_text(T0, 0), "2025-10-09 08:53");
assert_eq!(time_text(T0, 120), "2025-10-09 10:53");
assert_eq!(time_text(T0, -540), "2025-10-08 23:53");
// 2025-10-09T08:53:20Z; the UTC day began at 00:00Z.
assert_eq!(start_of_day_ms(T0, 0), 1_759_968_000_000);
// At UTC+2 the local day began at 22:00Z the evening before.
assert_eq!(start_of_day_ms(T0, 120), 1_759_968_000_000 - 2 * HOUR);
// At UTC-9 the local day (Oct 8) began at 09:00Z on Oct 8.
assert_eq!(start_of_day_ms(T0, -540), 1_759_968_000_000 - 24 * HOUR + 9 * HOUR);
assert_eq!(start_of_day_ms(0, 0), 0);
}
#[test]
fn days_convert_to_and_from_the_epoch_count_both_ways() {
for ms in [0, 951_782_400_000, 1_709_164_800_000, 1_767_225_599_000, T0] {
@@ -232,41 +103,3 @@ fn days_convert_to_and_from_the_epoch_count_both_ways() {
}
const DAY_MS_FOR_TESTS: u64 = 86_400_000;
#[test]
fn the_daily_series_fills_empty_days_and_keeps_the_most_recent() {
let day = DAY_MS_FOR_TESTS;
let e = entries(&[
("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)),
("b", T0 + 3 * day, "p", "m", Some(Outcome::Done), Some(5_000)),
("c", T0 + 3 * day + 1, "p", "m", None, None),
]);
let refs: Vec<&HistoryEntry> = e.iter().collect();
let all = daily(&refs, 0, 31);
let shape: Vec<(String, usize)> = all.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect();
assert_eq!(shape, [("2025-10-09".to_owned(), 1), ("2025-10-10".to_owned(), 0), ("2025-10-11".to_owned(), 0), ("2025-10-12".to_owned(), 2)]);
let recent = daily(&refs, 0, 2);
let shape: Vec<String> = recent.iter().map(|(d, _)| d.to_string()).collect();
assert_eq!(shape, ["2025-10-11", "2025-10-12"]);
assert!(daily(&[], 0, 31).is_empty());
}
#[test]
fn models_and_apps_group_busiest_first_and_average_only_successful_timed_jobs() {
let e = entries(&[
("a", T0, "photocraft", "flux", Some(Outcome::Done), Some(50_000)),
("b", T0 + 10, "photocraft", "flux", Some(Outcome::Done), Some(50_000)),
("c", T0 + 20, "wordcraft", "gpt", Some(Outcome::Done), Some(1_000)),
("d", T0 + 30, "wordcraft", "gpt", Some(Outcome::Failed { kind: ErrorKind::Network }), None),
("e", T0 + 40, "wordcraft", "gpt", None, None),
]);
let refs: Vec<&HistoryEntry> = e.iter().collect();
let models = by_model(&refs);
assert_eq!(models.iter().map(|(k, t)| (k.as_str(), t.jobs)).collect::<Vec<_>>(), [("gpt", 3), ("flux", 2)]);
let apps = by_app(&refs);
assert_eq!(apps[0].0, "wordcraft");
// Each finished job took two seconds in the fixture; the failed and unfinished ones do not count.
assert_eq!(models[0].1.average_ms(), Some(2_000));
assert_eq!(models[0].1.timed, 1);
assert_eq!(Totals::default().average_ms(), None);
}
-114
View File
@@ -1,114 +0,0 @@
use super::*;
fn start(run: &str, at_ms: u64) -> StartRecord {
StartRecord {
v: HISTORY_SCHEMA,
run: run.into(),
at_ms,
app: "photocraft".into(),
role_id: "fill".into(),
role_label: "Generative Fill".into(),
capability: "image.inpaint".into(),
connection: "conn1".into(),
connection_label: "Hosted".into(),
model: "m1".into(),
locality: Locality::Remote,
destination: "https://api.example.com".into(),
sent: Vec::new(),
params: vec!["seed".into()],
provider_job: Some("gen-9".into()),
estimate: None,
prompt: None,
}
}
fn end(run: &str, at_ms: u64, outcome: Outcome) -> EndRecord {
EndRecord { v: HISTORY_SCHEMA, run: run.into(), at_ms, outcome, usage: None }
}
fn s(r: StartRecord) -> HistoryRecord {
HistoryRecord::Start(r)
}
fn e(r: EndRecord) -> HistoryRecord {
HistoryRecord::End(r)
}
#[test]
fn a_line_round_trips_and_leaves_out_what_is_absent() {
let line = serde_json::to_string(&s(start("a", 5))).unwrap();
assert!(!line.contains('\n'));
assert!(!line.contains("prompt"), "{line}");
assert!(!line.contains("estimate"), "{line}");
assert_eq!(serde_json::from_str::<HistoryRecord>(&line).unwrap(), s(start("a", 5)));
let failed = e(end("a", 9, Outcome::Failed { kind: ErrorKind::Quota }));
let line = serde_json::to_string(&failed).unwrap();
assert!(line.contains("\"phase\":\"end\""), "{line}");
assert_eq!(serde_json::from_str::<HistoryRecord>(&line).unwrap(), failed);
}
#[test]
fn an_unknown_phase_does_not_parse_so_readers_can_skip_it() {
assert!(serde_json::from_str::<HistoryRecord>(r#"{"phase":"pause","run":"a"}"#).is_err());
}
#[test]
fn start_and_end_join_by_run_and_the_list_is_newest_first() {
let log = merge(vec![s(start("old", 10)), s(start("new", 30)), e(end("new", 45, Outcome::Done)), e(end("old", 12, Outcome::Cancelled))], 0);
let runs: Vec<_> = log.entries.iter().map(|x| x.start.run.as_str()).collect();
assert_eq!(runs, ["new", "old"]);
assert_eq!(log.entries[0].duration_ms(), Some(15));
assert_eq!(log.entries[1].outcome(), Some(&Outcome::Cancelled));
}
#[test]
fn a_start_with_no_end_stays_unfinished() {
let log = merge(vec![s(start("a", 10))], 0);
assert_eq!(log.entries.len(), 1);
assert_eq!(log.entries[0].outcome(), None);
assert_eq!(log.entries[0].duration_ms(), None);
}
#[test]
fn an_end_whose_start_was_rotated_away_is_dropped() {
let log = merge(vec![e(end("gone", 5, Outcome::Done))], 2);
assert!(log.entries.is_empty());
assert_eq!(log.skipped, 2);
}
#[test]
fn the_first_end_wins_and_a_repeated_start_is_ignored() {
let log = merge(vec![s(start("a", 10)), s(start("a", 99)), e(end("a", 20, Outcome::Done)), e(end("a", 30, Outcome::Cancelled))], 0);
assert_eq!(log.entries.len(), 1);
assert_eq!(log.entries[0].start.at_ms, 10);
assert_eq!(log.entries[0].outcome(), Some(&Outcome::Done));
}
#[test]
fn a_clock_that_went_backwards_gives_no_duration() {
let log = merge(vec![s(start("a", 50)), e(end("a", 40, Outcome::Done))], 0);
assert_eq!(log.entries[0].duration_ms(), None);
}
#[test]
fn cost_is_only_what_the_provider_reported() {
let mut finished = end("a", 20, Outcome::Done);
let mut log = merge(vec![s(start("a", 10)), e(finished.clone())], 0);
assert_eq!(log.entries[0].reported_cost(), None);
finished.usage = Some(Usage { cost_micros: Some(40_000), currency: None, ..Usage::default() });
log = merge(vec![s(start("a", 10)), e(finished.clone())], 0);
assert_eq!(log.entries[0].reported_cost(), None, "no currency, no cost");
finished.usage = Some(Usage { cost_micros: Some(40_000), currency: Some("USD".into()), ..Usage::default() });
log = merge(vec![s(start("a", 10)), e(finished)], 0);
assert_eq!(log.entries[0].reported_cost(), Some((40_000, "USD")));
}
#[test]
fn prompts_are_clipped_on_a_character_boundary() {
let long = "é".repeat(MAX_PROMPT_CHARS + 50);
let clipped = clip_prompt(&long);
assert_eq!(clipped.chars().count(), MAX_PROMPT_CHARS);
assert_eq!(clip_prompt("short"), "short");
}
+16 -41
View File
@@ -13,9 +13,18 @@ pub const MAX_ID_LEN: usize = 128;
/// Why a string was refused as an identifier.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum IdError {
/// The value is empty.
Empty,
TooLong { len: usize, max: usize },
/// The value is longer than the limit.
TooLong {
/// Length of the value in bytes.
len: usize,
/// Longest allowed length in bytes.
max: usize,
},
/// The value contains a character outside the allowed set.
BadChar(char),
/// The value is the wrong shape. The text says how.
Malformed(&'static str),
}
@@ -71,6 +80,7 @@ macro_rules! validated_string {
Ok(Self(value))
}
/// The wrapped string.
pub fn as_str(&self) -> &str {
&self.0
}
@@ -118,12 +128,16 @@ macro_rules! open_enum {
$(#[$m])*
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum $name {
$($var,)+
$(
#[allow(missing_docs)]
$var,
)+
/// A well-formed value this library does not know by name.
Other(String),
}
impl $name {
/// The well-known name, or the text of `Other`.
pub fn as_str(&self) -> &str {
match self {
$(Self::$var => $text,)+
@@ -197,42 +211,3 @@ validated_string!(
SecretRef,
validate_id
);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_accept_normal_values() {
assert!(ModelId::new("black-forest-labs/flux-1.1-pro").is_ok());
assert!(ConnectionId::new("conn_01hx").is_ok());
}
#[test]
fn ids_reject_bad_values_without_panicking() {
assert_eq!(ModelId::new(""), Err(IdError::Empty));
assert_eq!(ModelId::new("a b"), Err(IdError::BadChar(' ')));
assert_eq!(ModelId::new("a\0b"), Err(IdError::BadChar('\0')));
assert!(matches!(ModelId::new("x".repeat(MAX_ID_LEN + 1)), Err(IdError::TooLong { .. })));
assert!(ModelId::new("\u{202e}rtl").is_err());
}
#[test]
fn tokens_reject_dots() {
assert!(validate_token("image").is_ok());
assert_eq!(validate_token("a.b"), Err(IdError::BadChar('.')));
}
#[test]
fn deserialize_validates() {
let ok: Result<ModelId, _> = serde_json::from_str("\"gpt-image-1\"");
assert!(ok.is_ok());
let bad: Result<ModelId, _> = serde_json::from_str("\"has space\"");
assert!(bad.is_err());
}
#[test]
fn debug_shows_type_and_value() {
assert_eq!(format!("{:?}", AppId::new("photocraft").unwrap()), "AppId(\"photocraft\")");
}
}
+36 -59
View File
@@ -15,19 +15,26 @@ use crate::payload::Payload;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum JobState {
/// Accepted by the provider but not started.
Queued,
/// `percent` is 0 to 100 when the provider reports it.
Running {
/// Progress from 0 to 100, when the provider reports it.
percent: Option<u8>,
},
/// Finished with outputs. Final.
Succeeded,
/// Ended with an error. Final.
Failed {
/// Why the job failed.
error: AiError,
},
/// Stopped on request. Final.
Cancelled,
}
impl JobState {
/// True for succeeded, failed and cancelled, the states that never change.
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Succeeded | Self::Failed { .. } | Self::Cancelled)
}
@@ -53,6 +60,7 @@ impl JobState {
/// A finished result.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Output {
/// The result data.
pub payload: Payload,
/// Optional note such as "variation 2". Structured output arrives as an `application/json`
/// inline payload.
@@ -64,41 +72,66 @@ pub struct Output {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
TextDelta { text: String },
ToolCall { name: String, arguments: String },
/// A piece of generated text, to append to what came before.
TextDelta {
/// The new text.
text: String,
},
/// The model asked to call a tool.
ToolCall {
/// Name of the tool.
name: String,
/// The arguments, as a JSON string.
arguments: String,
},
/// A finished output.
Output(Output),
Notice { message: String },
/// A message from the provider for the user, not part of the result.
Notice {
/// The message text.
message: String,
},
}
/// What a provider charged or counted. All fields optional: many providers report none.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Usage {
/// Input the provider counted, in its own units (for example tokens).
pub input_units: Option<u64>,
/// Output the provider counted, in its own units.
pub output_units: Option<u64>,
/// Millionths of `currency`, so no floating point money.
pub cost_micros: Option<u64>,
/// Currency code for `cost_micros`, such as `USD`.
pub currency: Option<String>,
}
/// A price estimate shown before a job runs.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CostEstimate {
/// Estimated price in millionths of `currency`.
pub micros: u64,
/// Currency code, such as `USD`.
pub currency: String,
/// How the job will be billed.
pub billing: Billing,
}
/// One poll's answer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct JobSnapshot {
/// Where the job is now.
pub state: JobState,
/// Events since the previous poll, oldest first.
#[serde(default)]
pub events: Vec<Event>,
/// What the provider reported charging, when it did.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Usage>,
}
impl JobSnapshot {
/// A snapshot with the given state and no events or usage.
pub fn new(state: JobState) -> Self {
Self { state, events: Vec::new(), usage: None }
}
@@ -111,59 +144,3 @@ impl JobSnapshot {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use JobState::{Cancelled, Failed, Queued, Running, Succeeded};
fn failed() -> JobState {
Failed { error: AiError::new(crate::error::ErrorKind::Provider, "boom") }
}
#[test]
fn forward_moves_are_legal() {
assert!(Queued.can_become(&Running { percent: None }));
assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(10) }));
assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(80) }));
assert!(Running { percent: Some(80) }.can_become(&Succeeded));
assert!(Running { percent: None }.can_become(&failed()));
assert!(Queued.can_become(&Succeeded));
}
#[test]
fn progress_cannot_go_backwards() {
assert!(!Running { percent: Some(50) }.can_become(&Running { percent: Some(40) }));
assert!(!Running { percent: Some(50) }.can_become(&Running { percent: None }));
assert!(!Running { percent: Some(5) }.can_become(&Queued));
}
#[test]
fn terminal_states_are_final() {
for t in [Succeeded, Cancelled, failed()] {
assert!(t.is_terminal());
assert!(t.can_become(&t.clone()));
assert!(!t.can_become(&Running { percent: None }));
assert!(!t.can_become(&Queued));
}
assert!(!Succeeded.can_become(&Cancelled));
assert!(!Cancelled.can_become(&Succeeded));
}
#[test]
fn snapshot_collects_outputs_only() {
let mut s = JobSnapshot::new(Succeeded);
s.events.push(Event::TextDelta { text: "hi".into() });
s.events.push(Event::Output(Output { payload: Payload::text("done"), label: None }));
assert_eq!(s.outputs().count(), 1);
}
#[test]
fn snapshot_json_round_trip() {
let mut s = JobSnapshot::new(Running { percent: Some(40) });
s.events.push(Event::ToolCall { name: "lookup".into(), arguments: "{}".into() });
s.usage = Some(Usage { cost_micros: Some(1200), currency: Some("USD".into()), ..Usage::default() });
let json = serde_json::to_string(&s).unwrap();
assert_eq!(serde_json::from_str::<JobSnapshot>(&json).unwrap(), s);
}
}
+8 -1
View File
@@ -28,7 +28,7 @@
//! | [`spec`] | a provider described as data: types, checker and substitutions (task u2) |
//! | [`provider`] | the [`Provider`] trait |
//! | [`mock`], [`conformance`] | scripted provider and reusable behaviour checks |
#![warn(missing_docs)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod capability;
@@ -68,3 +68,10 @@ pub use request::Request;
pub use role::{Binding, Role};
pub use secret::SecretString;
pub use store::StoreFile;
#[cfg(test)]
extern crate self as craft_ai_core;
#[cfg(test)]
#[path = "../tests/main.rs"]
mod integration;
+4
View File
@@ -18,7 +18,9 @@ use crate::request::Request;
/// How a mock job ends.
#[derive(Clone, Debug)]
pub enum Outcome {
/// Finish successfully with these outputs.
Succeed(Vec<Output>),
/// Finish in the `Failed` state with this error.
Fail(AiError),
}
@@ -29,6 +31,7 @@ pub struct Script {
pub running_polls: u32,
/// One text delta is emitted per poll until these run out.
pub text_chunks: Vec<String>,
/// How the job ends once the running polls and text chunks are done.
pub outcome: Outcome,
}
@@ -61,6 +64,7 @@ pub struct MockProvider {
}
impl MockProvider {
/// Builds a provider that offers `models` and runs every job by `script`.
pub fn new(models: Vec<ModelInfo>, script: Script) -> Self {
Self { models, script, limits: Limits::default(), state: Mutex::new(State::default()) }
}
+17 -65
View File
@@ -27,10 +27,13 @@ open_enum!(
/// Optional abilities beyond the basic request and result.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Features {
/// The model can stream text deltas as it generates.
#[serde(default)]
pub streaming: bool,
/// The model can call tools.
#[serde(default)]
pub tools: bool,
/// The model can return JSON that follows a schema.
#[serde(default)]
pub structured_output: bool,
}
@@ -38,6 +41,7 @@ pub struct Features {
/// What one model can do for one capability.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilitySpec {
/// The capability this spec describes.
pub capability: CapabilityId,
/// Inputs the model accepts, with the most of each. An input role not listed is unsupported.
pub accepts: BTreeMap<InputRole, u32>,
@@ -47,6 +51,7 @@ pub struct CapabilitySpec {
/// Most outputs one request can return (variations count here).
#[serde(default = "one")]
pub max_outputs: u32,
/// Optional abilities the model has for this capability.
#[serde(default)]
pub features: Features,
}
@@ -56,16 +61,19 @@ fn one() -> u32 {
}
impl CapabilitySpec {
/// A spec that accepts the given inputs (one of each) and requires none.
/// A spec for `capability` that accepts no inputs, requires none and returns one output; add
/// inputs with [`accepting`](Self::accepting).
pub fn new(capability: CapabilityId) -> Self {
Self { capability, accepts: BTreeMap::new(), requires: Vec::new(), max_outputs: 1, features: Features::default() }
}
/// Accepts up to `max` inputs of `role`.
pub fn accepting(mut self, role: InputRole, max: u32) -> Self {
self.accepts.insert(role, max);
self
}
/// Requires an input of `role`. Adding the same role twice has no effect.
pub fn requiring(mut self, role: InputRole) -> Self {
if !self.requires.contains(&role) {
self.requires.push(role);
@@ -73,11 +81,13 @@ impl CapabilitySpec {
self
}
/// Sets the most outputs one request can return.
pub fn max_outputs(mut self, n: u32) -> Self {
self.max_outputs = n;
self
}
/// Sets the optional abilities.
pub fn with_features(mut self, features: Features) -> Self {
self.features = features;
self
@@ -102,8 +112,11 @@ pub struct Pricing {
/// One model as offered by one connection.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelInfo {
#[allow(missing_docs)]
pub id: ModelId,
/// Name shown to the user.
pub label: String,
/// What the model can do, one spec per capability.
#[serde(default)]
pub capabilities: Vec<CapabilitySpec>,
/// Reported by the provider where it can be (OpenRouter does). Absent in stores written before
@@ -123,80 +136,19 @@ pub struct ModelInfo {
}
impl ModelInfo {
/// Builds a model with no capabilities. Add them with [`ModelInfo::with`].
pub fn new(id: ModelId, label: impl Into<String>) -> Self {
Self { id, label: label.into(), capabilities: Vec::new(), pricing: None, released: None, tags: Vec::new(), local_file: None }
}
/// Adds a capability spec.
pub fn with(mut self, spec: CapabilitySpec) -> Self {
self.capabilities.push(spec);
self
}
/// The spec for `capability`, if the model supports it.
pub fn spec_for(&self, capability: &CapabilityId) -> Option<&CapabilitySpec> {
self.capabilities.iter().find(|s| &s.capability == capability)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cap(s: &str) -> CapabilityId {
CapabilityId::parse(s).unwrap()
}
#[test]
fn a_store_written_before_pricing_existed_still_loads_and_leaves_it_out_when_absent() {
let old = r#"{"id":"gpt-4o","label":"gpt-4o","capabilities":[]}"#;
let info: ModelInfo = serde_json::from_str(old).unwrap();
assert_eq!((info.pricing.clone(), info.released, info.tags.clone()), (None, None, Vec::new()));
let again = serde_json::to_string(&info).unwrap();
assert!(!again.contains("pricing") && !again.contains("released") && !again.contains("tags"), "{again}");
let priced = ModelInfo {
pricing: Some(Pricing { per_image_micros: Some(40_000), ..Pricing::default() }),
released: Some(1_760_000_000),
tags: vec!["recommended".into()],
..info
};
let back: ModelInfo = serde_json::from_str(&serde_json::to_string(&priced).unwrap()).unwrap();
assert_eq!(back, priced);
}
#[test]
fn input_roles_round_trip_including_custom() {
for text in ["mask", "reference", "depth-map"] {
let r = InputRole::parse(text).unwrap();
assert_eq!(r.as_str(), text);
assert_eq!(serde_json::from_str::<InputRole>(&serde_json::to_string(&r).unwrap()).unwrap(), r);
}
assert!(InputRole::parse("bad role").is_err());
}
#[test]
fn spec_round_trips_with_map_keys() {
let spec = CapabilitySpec::new(cap("image.inpaint"))
.accepting(InputRole::Source, 1)
.accepting(InputRole::Mask, 1)
.accepting(InputRole::Reference, 3)
.requiring(InputRole::Source)
.max_outputs(4);
let json = serde_json::to_string(&spec).unwrap();
assert!(json.contains("\"reference\":3"));
assert_eq!(serde_json::from_str::<CapabilitySpec>(&json).unwrap(), spec);
}
#[test]
fn missing_fields_take_defaults() {
let spec: CapabilitySpec = serde_json::from_str(r#"{"capability":"text.complete","accepts":{"prompt":1}}"#).unwrap();
assert_eq!(spec.max_outputs, 1);
assert!(!spec.features.streaming);
assert!(spec.requires.is_empty());
}
#[test]
fn model_finds_its_spec() {
let m = ModelInfo::new(ModelId::new("m1").unwrap(), "M1").with(CapabilitySpec::new(cap("image.generate")));
assert!(m.spec_for(&cap("image.generate")).is_some());
assert!(m.spec_for(&cap("image.inpaint")).is_none());
}
}
+22 -76
View File
@@ -18,7 +18,9 @@ const MAX_URI_LEN: usize = 4096;
/// Size limits applied to payloads in a request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
/// Largest inline binary payload, in bytes.
pub max_inline_bytes: u64,
/// Largest text payload, in bytes.
pub max_text_bytes: usize,
}
@@ -52,6 +54,7 @@ validated_string!(
);
impl MediaType {
/// The coarse kind for this media type. Unknown types are `Other`; `application/json` counts as text.
pub fn kind(&self) -> PayloadKind {
let s = self.as_str();
if s.starts_with("image/") {
@@ -75,19 +78,28 @@ impl MediaType {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PayloadKind {
#[allow(missing_docs)]
Text,
#[allow(missing_docs)]
Image,
#[allow(missing_docs)]
Video,
#[allow(missing_docs)]
Audio,
/// A document such as a PDF.
Document,
/// Any other media type.
Other,
}
/// A reference to data that stays where it is until a provider adapter streams it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PayloadHandle {
/// Where the data lives, such as a file path or URL. Never empty and has no control characters.
pub uri: String,
/// What the data is.
pub media_type: MediaType,
/// Size in bytes, when known.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size_bytes: Option<u64>,
}
@@ -96,27 +108,36 @@ pub struct PayloadHandle {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Payload {
/// Plain text.
Text {
/// The text.
text: String,
},
/// Binary data carried in the payload, serialized as base64.
Inline {
/// What the data is.
media_type: MediaType,
/// The raw bytes.
#[serde(with = "base64_bytes")]
data: Vec<u8>,
},
/// Data kept where it is, referenced by a handle.
Handle(PayloadHandle),
}
impl Payload {
/// A text payload.
pub fn text(text: impl Into<String>) -> Self {
Self::Text { text: text.into() }
}
/// An inline payload. Fails when `media_type` is not a valid media type.
pub fn inline(media_type: &str, data: Vec<u8>) -> Result<Self, AiError> {
let media_type = MediaType::new(media_type).map_err(|e| AiError::invalid(format!("media type: {e}")))?;
Ok(Self::Inline { media_type, data })
}
/// A handle payload. Fails on an empty, over-long (4096 bytes) or control-character URI, or an invalid media type.
pub fn handle(uri: &str, media_type: &str, size_bytes: Option<u64>) -> Result<Self, AiError> {
if uri.is_empty() || uri.len() > MAX_URI_LEN || uri.chars().any(char::is_control) {
return Err(AiError::invalid("payload uri is empty, too long, or has control characters"));
@@ -125,6 +146,7 @@ impl Payload {
Ok(Self::Handle(PayloadHandle { uri: uri.to_owned(), media_type, size_bytes }))
}
/// The coarse kind: text for `Text`, otherwise from the media type.
pub fn kind(&self) -> PayloadKind {
match self {
Self::Text { .. } => PayloadKind::Text,
@@ -224,79 +246,3 @@ mod base64_bytes {
super::base64_decode(&text).ok_or_else(|| serde::de::Error::custom("invalid base64"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base64_matches_known_vectors() {
for (raw, enc) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("foobar", "Zm9vYmFy")] {
assert_eq!(base64_encode(raw.as_bytes()), enc);
assert_eq!(base64_decode(enc).unwrap(), raw.as_bytes());
}
}
#[test]
fn base64_round_trips_all_byte_values() {
let data: Vec<u8> = (0..=255u8).collect();
assert_eq!(base64_decode(&base64_encode(&data)).unwrap(), data);
}
#[test]
fn base64_rejects_malformed() {
for bad in ["Zg=", "Z", "Zm9v!", "=Zm9", "Zg==Zg==", "Zm=v", "Z===", "Zm9v\n"] {
assert!(base64_decode(bad).is_none(), "{bad:?}");
}
}
#[test]
fn media_type_validation() {
assert!(MediaType::new("image/png").is_ok());
assert!(MediaType::new("application/vnd.api+json").is_ok());
for bad in ["", "png", "image/", "/png", "Image/PNG", "image/png/x", "image/p ng"] {
assert!(MediaType::new(bad).is_err(), "{bad:?}");
}
}
#[test]
fn kinds_follow_media_type() {
assert_eq!(Payload::inline("image/png", vec![1]).unwrap().kind(), PayloadKind::Image);
assert_eq!(Payload::inline("application/pdf", vec![1]).unwrap().kind(), PayloadKind::Document);
assert_eq!(Payload::text("hi").kind(), PayloadKind::Text);
}
#[test]
fn inline_over_limit_is_refused_with_a_hint() {
let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 };
let err = Payload::inline("image/png", vec![0; 5]).unwrap().check(&limits).unwrap_err();
assert!(err.message.contains("handle"));
assert!(Payload::text("12345").check(&limits).is_err());
assert!(Payload::text("1234").check(&limits).is_ok());
}
#[test]
fn handles_skip_the_inline_limit() {
let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 };
let h = Payload::handle("file:///big.mov", "video/quicktime", Some(10_000_000_000)).unwrap();
assert!(h.check(&limits).is_ok());
assert_eq!(h.size_hint(), Some(10_000_000_000));
}
#[test]
fn handle_rejects_bad_uris() {
assert!(Payload::handle("", "video/mp4", None).is_err());
assert!(Payload::handle("file:///a\nb", "video/mp4", None).is_err());
assert!(Payload::handle(&"x".repeat(MAX_URI_LEN + 1), "video/mp4", None).is_err());
}
#[test]
fn json_round_trip() {
let p = Payload::inline("image/png", vec![0, 1, 2, 250, 255]).unwrap();
let json = serde_json::to_string(&p).unwrap();
assert!(json.contains("\"type\":\"inline\""));
assert_eq!(serde_json::from_str::<Payload>(&json).unwrap(), p);
let bad = r#"{"type":"inline","media_type":"image/png","data":"!!"}"#;
assert!(serde_json::from_str::<Payload>(bad).is_err());
}
}
+17 -3
View File
@@ -27,10 +27,15 @@ pub const MAX_CATALOG_BYTES: usize = 256 * 1024;
pub enum Pick {
/// The one we would choose: a balance of quality, speed and price.
Recommended,
/// The model with the best output quality, as judged by whoever keeps the catalog.
BestResult,
/// The model with the lowest reported price.
LowestCost,
/// The model judged fastest, as kept in the catalog.
Fastest,
/// The most recently released model.
Newest,
/// The model judged most used, as kept in the catalog.
MostPopular,
}
@@ -43,6 +48,7 @@ impl Pick {
!matches!(self, Pick::LowestCost | Pick::Newest)
}
/// The stable text form, used in the catalog file.
pub fn key(self) -> &'static str {
match self {
Pick::Recommended => "recommended",
@@ -58,19 +64,23 @@ impl Pick {
/// One curated pick: for this job, on this kind of connection, this model earns this tag.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatalogEntry {
/// The capability the pick is for, as `<modality>.<task>`.
pub capability: String,
/// The tag it earns, as [`Pick::key`].
pub pick: String,
/// The connection's provider key, such as `openrouter`.
pub provider: String,
/// The model id.
pub model: String,
}
/// The curated picks. Earlier entries for the same job and tag win.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Catalog {
/// Catalog version. [`Catalog::over`] keeps the higher of the two.
#[serde(default)]
pub version: u32,
/// The picks. Earlier entries win over later ones for the same job and tag.
#[serde(default)]
pub entries: Vec<CatalogEntry>,
}
@@ -78,7 +88,9 @@ pub struct Catalog {
/// Why a catalog could not be used.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CatalogError {
/// The text is longer than [`MAX_CATALOG_BYTES`].
TooLarge,
/// The text is not valid catalog JSON. The string says why.
Syntax(String),
}
@@ -100,6 +112,7 @@ impl Catalog {
Self::from_json(include_str!("catalog.json")).unwrap_or_default()
}
/// Parses a catalog file. Fails when it is over [`MAX_CATALOG_BYTES`] or not valid JSON.
pub fn from_json(text: &str) -> Result<Self, CatalogError> {
if text.len() > MAX_CATALOG_BYTES {
return Err(CatalogError::TooLarge);
@@ -129,6 +142,7 @@ impl Catalog {
pub struct Candidate<'a> {
/// The connection's provider key.
pub provider: &'a str,
/// The model itself.
pub model: &'a ModelInfo,
/// Running it costs nothing (a local model, a free connection).
pub free: bool,
@@ -150,8 +164,11 @@ pub enum PickedBy {
/// A pick that was earned, and by which candidate (an index into the candidates given).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Picked {
/// The tag earned.
pub pick: Pick,
/// Index of the winning candidate in the slice that was ranked.
pub candidate: usize,
/// What earned it.
pub by: PickedBy,
}
@@ -211,6 +228,3 @@ fn newest(candidates: &[Candidate<'_>]) -> Option<(usize, PickedBy)> {
})
.map(|(i, at)| (i, PickedBy::Released(at)))
}
#[cfg(test)]
mod tests;
-166
View File
@@ -1,166 +0,0 @@
use super::*;
use crate::ids::ModelId;
fn cap(s: &str) -> CapabilityId {
CapabilityId::parse(s).unwrap()
}
fn model(id: &str, price: Option<u64>, released: Option<u64>) -> ModelInfo {
let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id);
m.pricing = price.map(|p| Pricing { per_image_micros: Some(p), ..Pricing::default() });
m.released = released;
m
}
fn cands<'a>(models: &'a [(&'a str, ModelInfo, bool)]) -> Vec<Candidate<'a>> {
models.iter().map(|(provider, model, free)| Candidate { provider, model, free: *free }).collect()
}
fn catalog(entries: &[(&str, &str, &str, &str)]) -> Catalog {
Catalog {
version: 1,
entries: entries
.iter()
.map(|(capability, pick, provider, model)| CatalogEntry {
capability: (*capability).into(),
pick: (*pick).into(),
provider: (*provider).into(),
model: (*model).into(),
})
.collect(),
}
}
fn find(picks: &[Picked], pick: Pick) -> Option<&Picked> {
picks.iter().find(|p| p.pick == pick)
}
#[test]
fn the_built_in_catalog_loads_and_starts_empty() {
let c = Catalog::builtin();
assert_eq!(c.version, 1);
assert!(c.entries.is_empty(), "no curated pick is claimed until it is checked");
}
#[test]
fn lowest_cost_and_newest_are_worked_out_from_what_is_reported() {
let models = [
("or", model("a-pricey", Some(80_000), Some(300)), false),
("or", model("b-cheap", Some(20_000), Some(100)), false),
("or", model("c-new", Some(50_000), Some(900)), false),
("or", model("d-unpriced", None, None), false),
];
let picks = choose(&cap("image.inpaint"), &cands(&models), &Catalog::default());
let cheapest = find(&picks, Pick::LowestCost).unwrap();
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(20_000)));
let newest = find(&picks, Pick::Newest).unwrap();
assert_eq!((newest.candidate, &newest.by), (2, &PickedBy::Released(900)));
assert!(find(&picks, Pick::Recommended).is_none(), "curated picks need the catalog");
}
#[test]
fn a_free_model_is_the_lowest_cost_and_unpriced_hosted_models_are_not_guessed_at() {
let models = [
("or", model("hosted", Some(1), None), false),
("comfyui", model("local-sdxl", None, None), true),
("or", model("unpriced", None, None), false),
];
let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default());
let cheapest = find(&picks, Pick::LowestCost).unwrap();
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Free));
let only_unpriced = [("or", model("x", None, None), false)];
let picks = choose(&cap("image.generate"), &cands(&only_unpriced), &Catalog::default());
assert!(picks.is_empty(), "no data, no pick: {picks:?}");
}
#[test]
fn text_models_compare_input_plus_output_per_million_tokens() {
let text = |id: &str, i: u64, o: u64| {
let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id);
m.pricing = Some(Pricing { input_micros_per_mtok: Some(i), output_micros_per_mtok: Some(o), per_image_micros: None });
m
};
let models = [("or", text("big", 3_000_000, 15_000_000), false), ("or", text("small", 150_000, 600_000), false)];
let picks = choose(&cap("text.complete"), &cands(&models), &Catalog::default());
let cheapest = find(&picks, Pick::LowestCost).unwrap();
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(750_000)));
}
#[test]
fn curated_picks_come_from_the_catalog_and_only_when_the_connection_offers_the_model() {
let models = [("or", model("flux-fill", None, None), false), ("bfl", model("flux-pro", None, None), false)];
let c = catalog(&[
// The first entry is for a model nobody offers, so it is skipped for the next.
("image.inpaint", "recommended", "or", "not-offered"),
("image.inpaint", "recommended", "bfl", "flux-pro"),
("image.inpaint", "best_result", "or", "flux-fill"),
// A model on the wrong provider does not match.
("image.inpaint", "fastest", "bfl", "flux-fill"),
// Another job's entry never leaks across.
("text.complete", "most_popular", "or", "flux-fill"),
]);
let picks = choose(&cap("image.inpaint"), &cands(&models), &c);
assert_eq!(find(&picks, Pick::Recommended).map(|p| p.candidate), Some(1));
assert_eq!(find(&picks, Pick::BestResult).map(|p| p.candidate), Some(0));
assert_eq!(find(&picks, Pick::Recommended).unwrap().by, PickedBy::Catalog);
assert!(find(&picks, Pick::Fastest).is_none());
assert!(find(&picks, Pick::MostPopular).is_none());
}
#[test]
fn a_model_that_disappears_stops_earning_its_pick() {
let c = catalog(&[("image.inpaint", "recommended", "or", "flux-fill")]);
let with = [("or", model("flux-fill", None, None), false)];
assert!(find(&choose(&cap("image.inpaint"), &cands(&with), &c), Pick::Recommended).is_some());
let without = [("or", model("something-else", None, None), false)];
assert!(choose(&cap("image.inpaint"), &cands(&without), &c).is_empty());
assert!(choose(&cap("image.inpaint"), &[], &c).is_empty());
}
#[test]
fn ties_go_to_the_id_that_sorts_first_so_the_answer_is_stable() {
let models = [("or", model("zeta", Some(10_000), Some(500)), false), ("or", model("alpha", Some(10_000), Some(500)), false)];
let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default());
assert_eq!(find(&picks, Pick::LowestCost).unwrap().candidate, 1);
assert_eq!(find(&picks, Pick::Newest).unwrap().candidate, 1);
}
#[test]
fn a_catalog_file_loads_and_a_bad_or_oversize_one_is_refused() {
let ok = r#"{"version":2,"entries":[{"capability":"image.inpaint","pick":"recommended","provider":"or","model":"m"},
{"capability":"image.inpaint","pick":"a_pick_from_the_future","provider":"or","model":"m"}]}"#;
let c = Catalog::from_json(ok).unwrap();
assert_eq!((c.version, c.entries.len()), (2, 2));
// The unknown tag is carried but can never match a known pick.
let models = [("or", model("m", None, None), false)];
let picks = choose(&cap("image.inpaint"), &cands(&models), &c);
assert_eq!(picks.len(), 1);
assert!(matches!(Catalog::from_json("not json"), Err(CatalogError::Syntax(_))));
assert_eq!(Catalog::from_json(&" ".repeat(MAX_CATALOG_BYTES + 1)), Err(CatalogError::TooLarge));
}
#[test]
fn which_picks_are_judgements_and_which_are_computed() {
let curated: Vec<_> = Pick::ALL.into_iter().filter(|p| p.is_curated()).collect();
assert_eq!(curated, [Pick::Recommended, Pick::BestResult, Pick::Fastest, Pick::MostPopular]);
let keys: std::collections::HashSet<_> = Pick::ALL.into_iter().map(Pick::key).collect();
assert_eq!(keys.len(), 6);
}
#[test]
fn a_newer_catalog_wins_over_the_built_in_one_and_the_rest_still_applies() {
let newer = catalog(&[("text.complete", "recommended", "openrouter", "model-new")]);
let built_in =
catalog(&[("text.complete", "recommended", "openrouter", "model-old"), ("text.complete", "best_result", "openrouter", "model-best")]);
let merged = newer.over(built_in);
let models = [
("openrouter", model("model-old", None, None), false),
("openrouter", model("model-new", None, None), false),
("openrouter", model("model-best", None, None), false),
];
let picks = choose(&cap("text.complete"), &cands(&models), &merged);
let by = |p: Pick| picks.iter().find(|x| x.pick == p).map(|x| x.candidate);
assert_eq!(by(Pick::Recommended), Some(1), "the newer entry wins");
assert_eq!(by(Pick::BestResult), Some(2), "an entry only the old one had still counts");
}
+9 -104
View File
@@ -21,14 +21,18 @@ pub const MAX_PARAMS_BYTES: usize = 64 * 1024;
/// One typed input.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Input {
/// What the input is for.
pub role: InputRole,
/// The data.
pub payload: Payload,
}
/// A unit of work for a model.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Request {
/// What the model is asked to do.
pub capability: CapabilityId,
/// The typed inputs, in the order given.
#[serde(default)]
pub inputs: Vec<Input>,
/// Provider-neutral options such as `seed` or `size`. Capped by [`MAX_PARAMS_BYTES`].
@@ -47,25 +51,30 @@ fn one() -> u32 {
}
impl Request {
/// A request for `capability` with no inputs or params, one output, and no streaming.
pub fn new(capability: CapabilityId) -> Self {
Self { capability, inputs: Vec::new(), params: Map::new(), outputs: 1, stream: false }
}
/// Adds an input.
pub fn with_input(mut self, role: InputRole, payload: Payload) -> Self {
self.inputs.push(Input { role, payload });
self
}
/// Sets a param, replacing any earlier value under `key`.
pub fn with_param(mut self, key: &str, value: Value) -> Self {
self.params.insert(key.to_owned(), value);
self
}
/// Sets how many results to return.
pub fn with_outputs(mut self, n: u32) -> Self {
self.outputs = n;
self
}
/// Asks for incremental results.
pub fn streaming(mut self) -> Self {
self.stream = true;
self
@@ -114,107 +123,3 @@ impl Request {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::ErrorKind;
use crate::model::Features;
fn cap(s: &str) -> CapabilityId {
CapabilityId::parse(s).unwrap()
}
fn png() -> Payload {
Payload::inline("image/png", vec![1, 2, 3]).unwrap()
}
fn inpaint_spec() -> CapabilitySpec {
CapabilitySpec::new(cap("image.inpaint"))
.accepting(InputRole::Prompt, 1)
.accepting(InputRole::Source, 1)
.accepting(InputRole::Mask, 1)
.accepting(InputRole::Reference, 1)
.requiring(InputRole::Source)
.requiring(InputRole::Mask)
.max_outputs(3)
}
fn good() -> Request {
Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png())
}
#[test]
fn a_well_formed_request_passes() {
assert!(good().with_input(InputRole::Prompt, Payload::text("a cat")).validate(&inpaint_spec(), &Limits::default()).is_ok());
}
#[test]
fn unsupported_input_is_a_clear_error() {
let spec = CapabilitySpec::new(cap("image.generate")).accepting(InputRole::Prompt, 1);
let req = Request::new(cap("image.generate")).with_input(InputRole::Mask, png());
let err = req.validate(&spec, &Limits::default()).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unsupported);
assert!(err.message.contains("mask"));
}
#[test]
fn too_many_references_are_counted_separately_from_masks() {
let req = good().with_input(InputRole::Reference, png()).with_input(InputRole::Reference, png());
let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err();
assert_eq!(err.kind, ErrorKind::Unsupported);
assert!(err.message.contains("reference"));
}
#[test]
fn missing_required_input_is_invalid() {
let req = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png());
let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err();
assert_eq!(err.kind, ErrorKind::InvalidRequest);
assert!(err.message.contains("mask"));
}
#[test]
fn output_count_is_bounded() {
assert!(good().with_outputs(3).validate(&inpaint_spec(), &Limits::default()).is_ok());
assert!(good().with_outputs(4).validate(&inpaint_spec(), &Limits::default()).is_err());
assert!(good().with_outputs(0).validate(&inpaint_spec(), &Limits::default()).is_err());
}
#[test]
fn streaming_needs_the_feature() {
let spec = CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1);
let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("hi")).streaming();
assert_eq!(req.validate(&spec, &Limits::default()).unwrap_err().kind, ErrorKind::Unsupported);
let spec = spec.with_features(Features { streaming: true, ..Features::default() });
assert!(req.validate(&spec, &Limits::default()).is_ok());
}
#[test]
fn capability_mismatch_is_invalid() {
let req = Request::new(cap("image.generate"));
assert_eq!(req.validate(&inpaint_spec(), &Limits::default()).unwrap_err().kind, ErrorKind::InvalidRequest);
}
#[test]
fn oversized_inline_input_is_refused() {
let limits = Limits { max_inline_bytes: 2, max_text_bytes: 10 };
assert!(good().validate(&inpaint_spec(), &limits).is_err());
}
#[test]
fn oversized_params_are_refused() {
let big = Value::String("x".repeat(MAX_PARAMS_BYTES + 1));
assert!(good().with_param("blob", big).validate(&inpaint_spec(), &Limits::default()).is_err());
}
#[test]
fn request_round_trips_and_defaults_apply() {
let req = good().with_param("seed", Value::from(7)).with_outputs(2);
let back: Request = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
assert_eq!(req, back);
let minimal: Request = serde_json::from_str(r#"{"capability":"image.generate"}"#).unwrap();
assert_eq!(minimal.outputs, 1);
assert!(!minimal.stream);
}
}
+41 -71
View File
@@ -19,8 +19,11 @@ use crate::model::{CapabilitySpec, InputRole, ModelInfo};
/// A feature an app offers that needs a model.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Role {
#[allow(missing_docs)]
pub id: RoleId,
/// Name shown to the user, such as "Generative Fill".
pub label: String,
/// The capability a model must offer to fill the role.
pub capability: CapabilityId,
/// Inputs this feature will send. A model must accept them and require no others.
#[serde(default)]
@@ -30,29 +33,63 @@ pub struct Role {
/// The user's choice for one role.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Binding {
/// The role being bound.
pub role: RoleId,
/// The chosen connection.
pub connection: ConnectionId,
/// The chosen model, offered by that connection.
pub model: ModelId,
}
/// A fully checked choice.
#[derive(Clone, Copy, Debug)]
pub struct Resolved<'a> {
/// The connection to send the job to.
pub connection: &'a Connection,
/// The model to run.
pub model: &'a ModelInfo,
/// The model's spec for the role's capability.
pub spec: &'a CapabilitySpec,
}
/// Why a role could not be resolved.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ResolveError {
/// No layer has a binding for the role.
Unbound(RoleId),
/// The bound connection is not in the list.
ConnectionMissing(ConnectionId),
/// The bound connection is switched off.
ConnectionDisabled(ConnectionId),
ModelMissing { connection: ConnectionId, model: ModelId },
CapabilityMismatch { model: ModelId, capability: CapabilityId },
InputUnsupported { model: ModelId, input: InputRole },
InputRequired { model: ModelId, input: InputRole },
/// The bound connection does not offer the bound model.
ModelMissing {
/// The bound connection.
connection: ConnectionId,
/// The bound model.
model: ModelId,
},
/// The model has no spec for the role's capability.
CapabilityMismatch {
/// The bound model.
model: ModelId,
/// The capability the role needs.
capability: CapabilityId,
},
/// The role sends an input the model does not accept.
InputUnsupported {
/// The bound model.
model: ModelId,
/// The input the model rejects.
input: InputRole,
},
/// The model requires an input the role does not send.
InputRequired {
/// The bound model.
model: ModelId,
/// The input the role is missing.
input: InputRole,
},
/// A tool role differs from the shared definition saved for its id.
ToolMismatch(RoleId),
}
@@ -157,21 +194,6 @@ mod tests {
Binding { role: RoleId::new("generative-fill").unwrap(), connection: ConnectionId::new(conn).unwrap(), model: ModelId::new("m").unwrap() }
}
#[test]
fn resolves_a_good_binding() {
let conns = [conn("a", true)];
let defaults = [bind("a")];
assert!(resolve(&role(), &[&[], &defaults], &conns).is_ok());
}
#[test]
fn app_override_beats_default() {
let conns = [conn("a", true), conn("b", true)];
let (over, def) = ([bind("b")], [bind("a")]);
let r = resolve(&role(), &[&over, &def], &conns).unwrap();
assert_eq!(r.connection.id.as_str(), "b");
}
#[test]
fn a_broken_override_is_an_error_and_never_falls_through() {
let conns = [conn("a", true)];
@@ -179,56 +201,4 @@ mod tests {
let err = resolve(&role(), &[&over, &def], &conns).unwrap_err();
assert!(matches!(err, ResolveError::ConnectionMissing(_)));
}
#[test]
fn unbound_and_disabled() {
let mut conns = [conn("a", true)];
assert!(matches!(resolve(&role(), &[&[]], &conns), Err(ResolveError::Unbound(_))));
conns[0].enabled = false;
assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ConnectionDisabled(_))));
}
#[test]
fn a_model_that_cannot_take_a_mask_does_not_resolve() {
let conns = [conn("a", false)];
let err = resolve(&role(), &[&[bind("a")]], &conns).unwrap_err();
assert!(matches!(err, ResolveError::InputUnsupported { input: InputRole::Mask, .. }));
}
#[test]
fn a_required_input_the_role_cannot_supply_has_a_specific_error() {
let mut conns = [conn("a", true)];
conns[0].models[0].capabilities[0].requires = vec![InputRole::Mask];
let mut r = role();
r.inputs = vec![InputRole::Source];
let err = resolve(&r, &[&[bind("a")]], &conns).unwrap_err();
assert!(matches!(err, ResolveError::InputRequired { input: InputRole::Mask, .. }));
assert_eq!(err.to_string(), "model m requires a 'mask' input that this tool does not provide");
}
#[test]
fn wrong_capability_and_missing_model() {
let mut conns = [conn("a", true)];
let mut r = role();
r.capability = cap("image.generate");
assert!(matches!(resolve(&r, &[&[bind("a")]], &conns), Err(ResolveError::CapabilityMismatch { .. })));
conns[0].models.clear();
assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ModelMissing { .. })));
}
#[test]
fn eligible_filters_by_capability_inputs_and_enabled() {
let mut off = conn("c", true);
off.enabled = false;
let conns = [conn("a", true), conn("b", false), off];
let list = eligible(&role(), &conns);
assert_eq!(list.len(), 1);
assert_eq!(list[0].connection.id.as_str(), "a");
}
#[test]
fn error_messages_read_well() {
let msg = ResolveError::Unbound(RoleId::new("x").unwrap()).to_string();
assert!(msg.contains("no model is chosen"));
}
}
+2 -21
View File
@@ -13,6 +13,7 @@ use std::fmt;
pub struct SecretString(String);
impl SecretString {
/// Wraps a secret value.
pub fn new(value: impl Into<String>) -> Self {
Self(value.into())
}
@@ -22,6 +23,7 @@ impl SecretString {
&self.0
}
/// True when the secret has no characters.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
@@ -73,21 +75,6 @@ pub fn redact(text: &str, secrets: &[&SecretString]) -> String {
mod tests {
use super::*;
#[test]
fn debug_and_display_never_show_the_value() {
let s = SecretString::new("sk-live-abc123");
assert!(!format!("{s:?}").contains("abc123"));
assert!(!format!("{s}").contains("abc123"));
assert!(!format!("{:?}", Some(&s)).contains("abc123"));
}
#[test]
fn redact_scrubs_every_occurrence() {
let s = SecretString::new("sk-live-abc123");
let out = redact("bad key sk-live-abc123 (sk-live-abc123)", &[&s]);
assert_eq!(out, "bad key [redacted] ([redacted])");
}
#[test]
fn redact_never_searches_its_own_markers() {
// Each secret matches the marker the one before it wrote; replacing in turn doubled the
@@ -105,10 +92,4 @@ mod tests {
assert_eq!(redact("xabcdx", &[&a, &b]), "x[redacted]x");
assert_eq!(redact("abcabc", &[&a]), "[redacted][redacted]");
}
#[test]
fn redact_ignores_empty_secret() {
let s = SecretString::new("");
assert_eq!(redact("hello", &[&s]), "hello");
}
}
+48 -2
View File
@@ -56,16 +56,23 @@ pub enum SpecAuth {
/// `Authorization: Bearer <key>`.
Bearer,
/// The key is the whole value of this header.
Header { name: String },
Header {
/// The header name. It must pass the same checks as a connection's key header.
name: String,
},
/// No key.
None,
}
/// HTTP methods a call may use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Method {
#[allow(missing_docs)]
Get,
#[allow(missing_docs)]
Post,
#[allow(missing_docs)]
Delete,
}
@@ -73,10 +80,14 @@ pub enum Method {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Call {
/// HTTP method.
pub method: Method,
/// Path joined to the spec's `base`. Starts with `/` and cannot name another host.
pub path: String,
/// Query parameters. Values may use the substitutions allowed for the call.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub query: BTreeMap<String, String>,
/// JSON body template. Substitutions apply inside its string values only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<Value>,
}
@@ -93,13 +104,16 @@ pub enum ExtractAs {
Text,
}
/// Where in a reply to find a result, and what kind of data it is.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Extract {
/// A JSON pointer (RFC 6901) into the reply.
pub at: String,
/// How to read the value at `at`. Written `as` in the spec file.
#[serde(rename = "as")]
pub kind: ExtractAs,
/// Media type of the result, such as `image/png`. Required for `base64` and `url`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub media_type: Option<String>,
}
@@ -108,40 +122,60 @@ pub struct Extract {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StateWord {
/// The provider has accepted the job but not started it.
Queued,
/// The job is in progress.
Running,
/// The job finished and the result is ready.
Succeeded,
/// The job failed.
Failed,
}
/// The call that starts a queued job.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Submit {
/// The call to make.
pub call: Call,
/// Pointer to the job id in the reply.
pub job_id_at: String,
}
/// The repeated call that checks a queued job and reads its result.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Poll {
/// The call to make. It may use `{job_id}`.
pub call: Call,
/// JSON pointer to the status word in the reply.
pub status_at: String,
/// Maps each status word the provider uses to one of the four states. A word not listed is an error.
pub states: BTreeMap<String, StateWord>,
/// Where to read the result once the job has succeeded.
pub result: Extract,
}
// A spec is loaded once and read many times; boxing the queue variant would only add noise.
/// How a request becomes a result: one call, or a submit and poll queue.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Flow {
/// One call whose reply holds the result.
RequestResponse { call: Call, result: Extract },
RequestResponse {
/// The one call to make.
call: Call,
/// Where the result is in the reply.
result: Extract,
},
/// Submit, then ask for the result until it is ready.
Queue {
/// The call that starts the job.
submit: Submit,
/// The call that checks it.
poll: Poll,
/// Optional call that cancels the job.
#[serde(default, skip_serializing_if = "Option::is_none")]
cancel: Option<Call>,
},
@@ -151,13 +185,18 @@ pub enum Flow {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SpecModel {
/// Model id, as the provider names it. Must be a valid [`ModelId`].
pub id: String,
/// Name shown to the user.
pub label: String,
/// The capability the model offers, as `<modality>.<task>`.
pub capability: String,
/// Input role to the most of it the model takes.
pub accepts: BTreeMap<String, u32>,
/// Input roles that must be sent. Every model must require `prompt`.
#[serde(default)]
pub requires: Vec<String>,
/// Most outputs one request can return. Defaults to 1.
#[serde(default = "one")]
pub max_outputs: u32,
}
@@ -196,18 +235,25 @@ impl Default for SpecLimits {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Spec {
/// Must equal [`SPEC_VERSION`].
pub spec_version: u32,
/// Id for the connection this spec makes. Must be a valid [`ConnectionId`](crate::ids::ConnectionId).
pub id: String,
/// Name shown to the user, 1 to 120 plain characters.
pub label: String,
/// `https://host[/prefix]`, or `http://` for a loopback host.
pub base: String,
/// How the key is sent. Defaults to a bearer token.
#[serde(default = "bearer")]
pub auth: SpecAuth,
/// A free, read-only request for the Test button.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub probe: Option<Call>,
/// The models the spec offers, at most [`MAX_MODELS`].
pub models: Vec<SpecModel>,
/// How a request becomes a result.
pub flow: Flow,
/// Bounds on one job.
#[serde(default)]
pub limits: SpecLimits,
}
+1
View File
@@ -21,6 +21,7 @@ use crate::payload::validate_media_type;
pub struct SpecError {
/// Where in the spec, such as `flow.submit.call.path`.
pub at: String,
/// What is wrong and what to do about it, in plain words.
pub why: String,
}
+6
View File
@@ -9,8 +9,11 @@ use serde_json::Value;
/// A value a template may name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Slot {
/// The user's prompt text.
Prompt,
/// The model id.
Model,
/// The job id a submit call returned. Only calls after the submit may use it.
JobId,
}
@@ -28,8 +31,11 @@ impl Slot {
/// The values for one call. A slot left `None` cannot be used by that call.
#[derive(Clone, Copy, Debug, Default)]
pub struct Values<'a> {
/// Text for `{prompt}`.
pub prompt: Option<&'a str>,
/// Text for `{model}`.
pub model: Option<&'a str>,
/// Text for `{job_id}`.
pub job_id: Option<&'a str>,
}
+18 -89
View File
@@ -35,12 +35,15 @@ pub struct AppSettings {
/// The whole store.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoreFile {
/// Version of the file format, checked before anything else. [`SCHEMA_VERSION`] is the one this build writes.
pub schema_version: u32,
/// The saved connections. Ids must be unique.
#[serde(default)]
pub connections: Vec<Connection>,
/// Default bindings, set in the launcher, used by every app unless it overrides.
#[serde(default)]
pub defaults: Vec<Binding>,
/// Per-app settings, keyed by app id.
#[serde(default)]
pub apps: BTreeMap<AppId, AppSettings>,
/// User-declared tool contracts, shared across the suite. A declaration does not install an adapter.
@@ -51,23 +54,37 @@ pub struct StoreFile {
/// Why a store file was refused.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StoreError {
/// The file is over [`MAX_STORE_BYTES`].
TooLarge {
/// Size of the file in bytes.
len: usize,
/// The limit in bytes.
max: usize,
},
/// The file is not valid JSON for this schema. The string says why.
Syntax(String),
/// Written by a newer version. Do not write to it.
TooNew {
/// The file's schema version.
found: u32,
/// The newest schema version this build reads.
supported: u32,
},
/// The schema version is 0.
BadVersion(u32),
/// Two connections share this id.
DuplicateConnection(ConnectionId),
/// Two custom tools share this id.
DuplicateTool(RoleId),
/// More than 64 custom tools. The number is the count found.
TooManyTools(usize),
/// A custom tool has an empty or over-long label, or no inputs, more than 8, or a repeated one.
InvalidTool(RoleId),
/// A connection failed its own validation.
Invalid {
/// The connection that failed.
connection: ConnectionId,
/// The rule it broke.
why: ConnectionError,
},
}
@@ -152,6 +169,7 @@ impl StoreFile {
Ok(())
}
/// Serializes the store as pretty-printed JSON. Does not validate; call [`StoreFile::validate`] first.
pub fn to_json(&self) -> Result<String, StoreError> {
serde_json::to_string_pretty(self).map_err(|e| StoreError::Syntax(e.to_string()))
}
@@ -204,95 +222,6 @@ mod tests {
StoreFile { connections: vec![c], defaults: vec![binding], ..StoreFile::default() }
}
fn role() -> Role {
Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap(), inputs: vec![InputRole::Prompt] }
}
#[test]
fn round_trips() {
let s = store();
assert_eq!(StoreFile::parse(&s.to_json().unwrap()).unwrap(), s);
}
#[test]
fn unknown_fields_are_ignored() {
let mut v: serde_json::Value = serde_json::from_str(&store().to_json().unwrap()).unwrap();
v["added_in_a_later_release"] = serde_json::json!({"x": 1});
v["connections"][0]["new_flag"] = serde_json::json!(true);
assert!(StoreFile::parse(&v.to_string()).is_ok());
}
#[test]
fn a_newer_schema_is_refused_even_if_its_shape_changed() {
let text = r#"{"schema_version": 2, "connections": "now a different shape"}"#;
assert_eq!(StoreFile::parse(text), Err(StoreError::TooNew { found: 2, supported: SCHEMA_VERSION }));
}
#[test]
fn bad_input_is_an_error_not_a_panic() {
for text in
["", "not json", "[]", "{}", r#"{"schema_version": 0}"#, r#"{"schema_version": -1}"#, r#"{"schema_version": 1, "connections": [1]}"#]
{
assert!(StoreFile::parse(text).is_err(), "{text:?}");
}
let big = format!("{{\"schema_version\":1,\"pad\":\"{}\"}}", "x".repeat(MAX_STORE_BYTES));
assert!(matches!(StoreFile::parse(&big), Err(StoreError::TooLarge { .. })));
}
#[test]
fn a_mislabelled_connection_is_refused_at_load() {
let mut s = store();
s.connections[0].locality = crate::connection::Locality::Local;
let err = StoreFile::parse(&s.to_json().unwrap()).unwrap_err();
assert!(matches!(err, StoreError::Invalid { .. }));
}
#[test]
fn duplicate_connections_are_refused() {
let mut s = store();
s.connections.push(s.connections[0].clone());
assert!(matches!(s.validate(), Err(StoreError::DuplicateConnection(_))));
}
#[test]
fn resolve_uses_default_then_app_override() {
let mut s = store();
let app = AppId::new("wordcraft").unwrap();
assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "a");
let mut other = remote("b");
other.models = s.connections[0].models.clone();
s.connections.push(other);
let over = Binding { role: RoleId::new("rewrite").unwrap(), connection: ConnectionId::new("b").unwrap(), model: ModelId::new("m").unwrap() };
s.apps.insert(app.clone(), AppSettings { overrides: vec![over] });
assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "b");
assert_eq!(s.resolve(&AppId::new("photocraft").unwrap(), &role()).unwrap().connection.id.as_str(), "a");
}
#[test]
fn dangling_bindings_are_reported() {
let mut s = store();
s.connections.clear();
assert_eq!(s.dangling_bindings().len(), 1);
}
#[test]
fn truncated_and_mutated_files_never_panic() {
let text = store().to_json().unwrap();
for end in 0..=text.len() {
if text.is_char_boundary(end) {
let _ = StoreFile::parse(&text[..end]);
}
}
let bytes = text.as_bytes();
for i in (0..bytes.len()).step_by(7) {
let mut copy = bytes.to_vec();
copy[i] = copy[i].wrapping_add(1);
if let Ok(s) = String::from_utf8(copy) {
let _ = StoreFile::parse(&s);
}
}
}
#[test]
fn serialized_store_contains_no_secret_values() {
let json = store().to_json().unwrap();
+2 -170
View File
@@ -1,4 +1,5 @@
use craft_ai_core::role::{eligible, fits, resolve};
//! Integration tests of craft-ai-core: contract regressions.
use craft_ai_core::*;
fn draft(endpoint: &str) -> ConnectionDraft {
@@ -13,154 +14,6 @@ fn models(id: &str) -> Vec<ModelInfo> {
vec![ModelInfo::new(ModelId::new(id).unwrap(), id)]
}
#[test]
fn new_draft_discards_models_when_address_changes_after_probe() {
let mut draft = draft("https://a.example/v1");
assert!(draft.set_models("https://a.example/v1", models("a-only")));
draft.endpoint = "https://b.example/v1".into();
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
}
#[test]
fn returning_to_original_address_does_not_keep_another_addresses_models() {
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
let mut draft = ConnectionDraft::from_connection(&saved);
draft.endpoint = "https://b.example/v1".into();
assert!(draft.set_models("https://b.example/v1", models("b-only")));
draft.endpoint = "https://a.example/v1".into();
assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty());
}
#[test]
fn changing_model_contents_does_not_establish_address_provenance() {
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
let mut draft = ConnectionDraft::from_connection(&saved);
draft.models = models("refreshed-at-a");
draft.endpoint = "https://b.example/v1".into();
assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty());
}
#[test]
fn preset_models_belong_to_the_preset_address() {
let preset = PRESETS.iter().find(|preset| preset.key == "vertex-express").unwrap();
let mut draft = ConnectionDraft::from_preset(preset);
draft.key = "test-key".into();
assert!(!draft.prepare(&[]).unwrap().connection.models.is_empty());
draft.endpoint = "https://other.example/v1".into();
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
}
#[test]
fn a_fresh_test_at_each_address_keeps_its_models() {
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
let mut draft = ConnectionDraft::from_connection(&saved);
for address in ["https://b.example/v1", "https://a.example/v1", "https://c.example/v1"] {
draft.endpoint = format!(" {address} ");
assert!(draft.set_models(address, models("same-model")));
assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, models("same-model"));
}
}
#[test]
fn editing_and_returning_without_a_probe_preserves_original_models() {
let mut saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
saved.models = models("a-only");
let mut draft = ConnectionDraft::from_connection(&saved);
draft.endpoint = "https://b.example/v1".into();
assert!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
draft.endpoint = "https://a.example/v1".into();
assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models);
}
#[test]
fn custom_manual_models_still_work_for_a_new_connection_and_unchanged_address() {
let mut draft = ConnectionDraft::custom();
draft.endpoint = "https://custom.example/v1".into();
draft.uses_key = false;
draft.models = models("manual-model");
let saved = draft.prepare(&[]).unwrap().connection;
assert_eq!(saved.models, models("manual-model"));
let mut edited = ConnectionDraft::from_connection(&saved);
edited.models = models("other-manual-model");
assert_eq!(edited.prepare(&[saved]).unwrap().connection.models, models("other-manual-model"));
}
fn role_and_connection() -> (Role, Connection, Binding) {
let capability = CapabilityId::parse("image.inpaint").unwrap();
let role = Role {
id: RoleId::new("source-only").unwrap(),
label: "Source only".into(),
capability: capability.clone(),
inputs: vec![InputRole::Source],
};
let mut connection = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
connection.models = vec![
ModelInfo::new(ModelId::new("needs-mask").unwrap(), "Needs mask").with(
CapabilitySpec::new(capability)
.accepting(InputRole::Source, 1)
.accepting(InputRole::Mask, 1)
.requiring(InputRole::Source)
.requiring(InputRole::Mask),
),
];
let binding = Binding { role: role.id.clone(), connection: connection.id.clone(), model: connection.models[0].id.clone() };
(role, connection, binding)
}
#[test]
fn model_picker_excludes_inputs_the_tool_cannot_supply() {
let (role, connection, _) = role_and_connection();
let request = Request::new(role.capability.clone()).with_input(InputRole::Source, Payload::inline("image/png", vec![1]).unwrap());
assert!(request.validate(&connection.models[0].capabilities[0], &Limits::default()).is_err());
assert!(fits(&role, &connection.models[0]).is_none());
assert!(eligible(&role, &[connection]).is_empty());
}
#[test]
fn binding_resolution_rejects_inputs_the_tool_cannot_supply() {
let (role, connection, binding) = role_and_connection();
assert!(resolve(&role, &[&[binding]], &[connection]).is_err());
}
#[test]
fn required_inputs_resolve_when_supplied_and_optional_inputs_need_not_be_sent() {
let (mut role, mut connection, binding) = role_and_connection();
role.inputs.push(InputRole::Mask);
assert!(fits(&role, &connection.models[0]).is_some());
assert!(resolve(&role, &[std::slice::from_ref(&binding)], std::slice::from_ref(&connection)).is_ok());
role.inputs = vec![InputRole::Source];
connection.models[0].capabilities[0].requires = vec![InputRole::Source];
assert!(fits(&role, &connection.models[0]).is_some());
assert!(resolve(&role, &[&[binding]], &[connection]).is_ok());
}
#[test]
fn a_test_that_answers_after_the_address_moved_on_is_dropped() {
let mut draft = draft("https://a.example/v1");
// The test is started against a.example; the address is edited while it runs.
draft.endpoint = "https://b.example/v1".into();
assert!(!draft.set_models("https://a.example/v1", models("a-only")), "a late answer is not taken");
assert!(draft.models.is_empty(), "and it leaves the form's models alone");
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
}
#[test]
fn a_test_that_answers_while_its_address_still_stands_is_taken() {
let mut draft = draft("https://a.example/v1");
assert!(draft.set_models(" https://a.example/v1 ", models("a-only")), "whitespace is not a different address");
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only"));
}
#[test]
fn a_late_answer_does_not_overwrite_the_newer_address_own_models() {
let mut draft = draft("https://a.example/v1");
draft.endpoint = "https://b.example/v1".into();
// The test at b.example answers first; the older one at a.example arrives afterwards.
assert!(draft.set_models("https://b.example/v1", models("b-only")));
assert!(!draft.set_models("https://a.example/v1", models("a-only")));
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("b-only"), "the newer answer stands");
}
#[test]
fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() {
// Identity here is the address, not the test. After a.example → b.example → a.example, an
@@ -175,24 +28,3 @@ fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() {
assert!(draft.set_models("https://a.example/v1", models("a-only")), "an answer for the address on the form is taken");
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only"));
}
#[test]
fn a_refused_answer_leaves_models_already_on_the_form_untouched() {
let mut draft = draft("https://a.example/v1");
assert!(draft.set_models("https://a.example/v1", models("a-only")));
draft.endpoint = "https://b.example/v1".into();
assert!(!draft.set_models("https://a.example/v1", models("a-stale")));
assert_eq!(draft.models, models("a-only"), "the refused set is not written over the form");
}
#[test]
fn an_address_differing_only_in_case_or_a_trailing_slash_is_a_different_address() {
// The comparison is on the field's text, not a parsed URL: Endpoint drops the path, so
// /v1 and /v2 would look equal through it. Differing the other way is safe — the answer is
// refused and the person tests again — so this pins which way it fails.
for other in ["https://A.Example/v1", "https://a.example/v1/", "https://a.example/v2"] {
let mut draft = draft("https://a.example/v1");
assert!(!draft.set_models(other, models("x")), "{other} is not the field's address");
assert!(draft.models.is_empty());
}
}
+1 -70
View File
@@ -1,8 +1,7 @@
//! u1: the rules for a custom (unlisted, OpenAI-shaped) connection: a named key header, and what
//! a stored file may carry. The form is `ConnectionDraft`; these tests go through its public API.
use craft_ai_core::connection::ConnectionError;
use craft_ai_core::{Billing, Connection, ConnectionDraft, Field, KeyChange, Locality};
use craft_ai_core::{ConnectionDraft, Field};
fn custom(endpoint: &str, header: &str) -> ConnectionDraft {
let mut d = ConnectionDraft::custom();
@@ -13,42 +12,6 @@ fn custom(endpoint: &str, header: &str) -> ConnectionDraft {
d
}
#[test]
fn the_custom_form_starts_from_the_other_preset_with_billing_unknown() {
let d = ConnectionDraft::custom();
assert!(d.is_custom());
assert_eq!(d.provider, "openai-compatible");
assert_eq!(d.billing, Billing::Unknown);
assert!(d.uses_key);
assert!(d.key_header.is_empty());
assert!(d.models.is_empty());
}
#[test]
fn without_a_header_name_the_key_goes_as_a_bearer_token() {
let p = custom("https://gw.example.com/ai/v7", "").prepare(&[]).unwrap();
assert_eq!(p.connection.key_header, None);
let json = serde_json::to_string(&p.connection).unwrap();
assert!(!json.contains("key_header"), "{json}");
}
#[test]
fn a_named_header_is_kept_saved_and_edited_back() {
let p = custom("https://gw.example.com/ai/v7", " X-Api-Key ").prepare(&[]).unwrap();
assert_eq!(p.connection.key_header.as_deref(), Some("X-Api-Key"));
assert_eq!(p.connection.endpoint.as_deref(), Some("https://gw.example.com/ai/v7"));
assert_eq!(p.connection.locality, Locality::Remote);
assert!(matches!(p.key, KeyChange::Set(_)));
let again: Connection = serde_json::from_str(&serde_json::to_string(&p.connection).unwrap()).unwrap();
assert_eq!(again, p.connection);
let edit = ConnectionDraft::from_connection(&again);
assert_eq!(edit.key_header, "X-Api-Key");
let kept = edit.prepare(std::slice::from_ref(&again)).unwrap();
assert_eq!(kept.connection.key_header.as_deref(), Some("X-Api-Key"));
assert!(matches!(kept.key, KeyChange::Keep));
}
#[test]
fn header_names_that_could_break_the_request_are_refused() {
let long = "a".repeat(65);
@@ -74,35 +37,3 @@ fn header_names_that_could_break_the_request_are_refused() {
assert!(!e.message.contains("k-123"), "{bad:?}");
}
}
#[test]
fn ordinary_key_header_names_are_accepted() {
for ok in ["x-api-key", "api-key", "X-Goog-Api-Key", "apikey", "x_token"] {
custom("https://gw.example.com/v1", ok).prepare(&[]).unwrap_or_else(|e| panic!("{ok}: {e}"));
}
}
#[test]
fn a_header_name_without_a_key_is_refused() {
let mut d = custom("http://127.0.0.1:9000/v1", "x-api-key");
d.uses_key = false;
d.key.clear();
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::KeyHeader);
}
#[test]
fn a_stored_file_with_a_bad_header_name_is_refused_on_validate() {
let mut c = custom("https://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap().connection;
assert!(c.validate().is_ok());
c.key_header = Some("host".to_owned());
assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_))));
c.key_header = Some("x-api-key".to_owned());
c.auth = craft_ai_core::Auth::None;
assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_))));
}
#[test]
fn plain_http_to_a_remote_host_is_still_refused_for_a_custom_address() {
let e = custom("http://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap_err();
assert_eq!(e.field, Field::Address);
}
-69
View File
@@ -1,69 +0,0 @@
use craft_ai_core::{CapabilityId, InputRole, Role, RoleId, StoreFile};
fn tool(id: &str) -> Role {
Role {
id: RoleId::new(id).unwrap(),
label: "Describe photograph".into(),
capability: CapabilityId::parse("image.describe").unwrap(),
inputs: vec![InputRole::Source],
}
}
#[test]
fn duplicate_user_tool_ids_are_refused_before_the_store_is_written() {
let store = StoreFile { custom_tools: vec![tool("describe-photo"), tool("describe-photo")], ..StoreFile::default() };
assert!(store.validate().is_err());
}
#[test]
fn old_store_loads_and_user_tool_round_trips() {
let old = r#"{"schema_version":1,"connections":[],"defaults":[],"apps":{}}"#;
let mut store = StoreFile::parse(old).unwrap();
assert!(store.custom_tools.is_empty());
store.custom_tools.push(tool("describe-photo"));
let again = StoreFile::parse(&store.to_json().unwrap()).unwrap();
assert_eq!(again.custom_tools, store.custom_tools);
assert_eq!(again.custom_tools[0].capability.as_str(), "image.describe");
}
#[test]
fn hostile_tool_declarations_are_refused_on_load() {
let mut s = StoreFile { custom_tools: vec![tool("describe-photo"); 65], ..StoreFile::default() };
assert!(s.validate().is_err());
s.custom_tools.truncate(1);
s.custom_tools[0].inputs.push(InputRole::Source);
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
s.custom_tools[0].inputs = vec![InputRole::Source];
s.custom_tools[0].label = " \t ".into();
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
s.custom_tools[0].label = "x".repeat(121);
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
s.custom_tools[0].label = "Describe photograph".into();
s.custom_tools[0].inputs.clear();
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
}
#[test]
fn an_app_cannot_reinterpret_the_inputs_of_a_shared_custom_tool() {
use craft_ai_core::role::ResolveError;
use craft_ai_core::{AppId, Binding, CapabilitySpec, Connection, ConnectionId, ModelId, ModelInfo};
let shared = tool("describe-photo");
let model = ModelInfo::new(ModelId::new("m").unwrap(), "M").with(CapabilitySpec::new(shared.capability.clone()).accepting(InputRole::Source, 1));
let connection: Connection = serde_json::from_value(serde_json::json!({
"id":"service", "label":"Service", "provider":"test",
"endpoint":"http://127.0.0.1:9", "locality":"local", "auth":{"kind":"none"},
"billing":"free", "models":[model]
}))
.unwrap();
let store = StoreFile {
connections: vec![connection],
defaults: vec![Binding { role: shared.id.clone(), connection: ConnectionId::new("service").unwrap(), model: ModelId::new("m").unwrap() }],
custom_tools: vec![shared.clone()],
..StoreFile::default()
};
let app = AppId::new("photocraft").unwrap();
assert!(store.resolve(&app, &shared).is_ok());
let mut redefined = shared;
redefined.inputs.clear();
assert!(matches!(store.resolve(&app, &redefined), Err(ResolveError::ToolMismatch(_))));
}
+8
View File
@@ -0,0 +1,8 @@
//! Integration tests, built into the library's own test executable.
mod contract_regressions;
mod custom_connection;
mod mock_conformance;
mod spec_rules;
mod spec_support;
mod spec_template;
+2 -117
View File
@@ -1,12 +1,8 @@
//! Drives the mock provider through the shared conformance checks, and shows the model working
//! end to end the way an app would use it: declare roles, resolve through the store, check
//! consent, submit, poll, cancel. Also proves one library serves different modalities.
//! Drives the mock provider through the shared conformance checks.
use craft_ai_core::conformance::{run_cancel, run_lifecycle, run_rejects, run_unknown_job};
use craft_ai_core::consent::Disclosure;
use craft_ai_core::conformance::run_lifecycle;
use craft_ai_core::job::{Event, JobState, Output};
use craft_ai_core::mock::{MockProvider, Outcome, Script};
use craft_ai_core::role::{Binding, Role};
use craft_ai_core::*;
fn cap(s: &str) -> CapabilityId {
@@ -33,16 +29,6 @@ fn image_model() -> ModelInfo {
)
}
fn text_model() -> ModelInfo {
ModelInfo::new(model_id("txt"), "Text model").with(
CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1).accepting(InputRole::System, 1).with_features(Features {
streaming: true,
tools: true,
structured_output: true,
}),
)
}
fn inpaint_request() -> Request {
Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png()).with_outputs(2)
}
@@ -58,104 +44,3 @@ fn image_job_passes_the_lifecycle_and_returns_variations() {
assert_eq!(done.state, JobState::Succeeded);
assert_eq!(done.events.iter().filter(|e| matches!(e, Event::Output(_))).count(), 2);
}
#[test]
fn text_job_streams_deltas_in_order() {
let script = Script { text_chunks: vec!["Hel".into(), "lo ".into(), "world".into()], ..Script::default() };
let p = MockProvider::new(vec![text_model()], script);
let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("say hello")).streaming();
let done = run_lifecycle(&p, &model_id("txt"), &req).unwrap();
let text: String = done.events.iter().filter_map(|e| if let Event::TextDelta { text } = e { Some(text.as_str()) } else { None }).collect();
assert_eq!(text, "Hello world");
}
#[test]
fn failure_is_reported_with_its_kind() {
let err = AiError::new(ErrorKind::Quota, "out of credits");
let p = MockProvider::new(vec![image_model()], Script { outcome: Outcome::Fail(err.clone()), ..Script::default() });
let done = run_lifecycle(&p, &model_id("img"), &inpaint_request()).unwrap();
assert_eq!(done.state, JobState::Failed { error: err });
}
#[test]
fn cancel_mid_job_ends_cancelled() {
let p = MockProvider::new(vec![image_model()], Script { running_polls: 50, ..Script::default() });
run_cancel(&p, &model_id("img"), &inpaint_request()).unwrap();
}
#[test]
fn unsupported_requests_are_refused_before_sending() {
let p = MockProvider::new(vec![image_model(), text_model()], Script::default());
let with_reference = inpaint_request().with_input(InputRole::Reference, png());
run_rejects(&p, &model_id("img"), &with_reference, ErrorKind::Unsupported).unwrap();
let too_many = inpaint_request().with_outputs(9);
run_rejects(&p, &model_id("img"), &too_many, ErrorKind::Unsupported).unwrap();
let missing_mask = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png());
run_rejects(&p, &model_id("img"), &missing_mask, ErrorKind::InvalidRequest).unwrap();
let wrong_model = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("x"));
run_rejects(&p, &model_id("img"), &wrong_model, ErrorKind::Unsupported).unwrap();
}
#[test]
fn unknown_jobs_are_errors() {
run_unknown_job(&MockProvider::new(vec![image_model()], Script::default())).unwrap();
}
#[test]
fn an_app_flow_from_store_to_finished_job() {
// The launcher's store: one remote connection offering both models, defaults for two apps' roles.
let conn = Connection {
id: ConnectionId::new("conn1").unwrap(),
label: "My provider".into(),
provider: "http".into(),
endpoint: Some("https://api.example.com".into()),
locality: Locality::Remote,
auth: Auth::ApiKey { secret: SecretRef::new("secret-conn1").unwrap() },
billing: Billing::Metered,
models: vec![image_model(), text_model()],
enabled: true,
key_header: None,
};
let fill = Role {
id: RoleId::new("generative-fill").unwrap(),
label: "Generative Fill".into(),
capability: cap("image.inpaint"),
inputs: vec![InputRole::Source, InputRole::Mask],
};
let rewrite =
Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap("text.complete"), inputs: vec![InputRole::Prompt] };
let bind = |role: &Role, model: &str| Binding { role: role.id.clone(), connection: conn.id.clone(), model: model_id(model) };
let store = StoreFile { connections: vec![conn.clone()], defaults: vec![bind(&fill, "img"), bind(&rewrite, "txt")], ..StoreFile::default() };
let store = StoreFile::parse(&store.to_json().unwrap()).unwrap();
// Two different apps resolve their own roles from the same store.
let photocraft = AppId::new("photocraft").unwrap();
let wordcraft = AppId::new("wordcraft").unwrap();
let resolved = store.resolve(&photocraft, &fill).unwrap();
assert_eq!(resolved.model.id.as_str(), "img");
assert_eq!(store.resolve(&wordcraft, &rewrite).unwrap().model.id.as_str(), "txt");
// Consent is required for a remote connection, shows kinds and sizes, and is remembered.
let request = inpaint_request().with_input(InputRole::Prompt, Payload::text("remove the lamp"));
let disclosure = Disclosure::for_request(&photocraft, resolved.connection, &request);
let mut ledger = ConsentLedger::default();
assert!(ledger.needs_consent(&disclosure, 0));
ledger.grant(&disclosure);
assert!(!ledger.needs_consent(&disclosure, 0));
// Run it through a provider built from the same model list.
let provider = MockProvider::new(resolved.connection.models.clone(), Script { outcome: Outcome::Succeed(two_outputs()), ..Script::default() });
resolved.spec.validate_request(&request).unwrap();
let done = run_lifecycle(&provider, &resolved.model.id, &request).unwrap();
assert_eq!(done.state, JobState::Succeeded);
}
trait ValidateRequest {
fn validate_request(&self, r: &Request) -> Result<(), AiError>;
}
impl ValidateRequest for CapabilitySpec {
fn validate_request(&self, r: &Request) -> Result<(), AiError> {
r.validate(self, &Limits::default())
}
}
-74
View File
@@ -1,74 +0,0 @@
//! How calls may use substitutions and what a flow must send (task u2). Each case feeds an input
//! that only the named rule refuses.
mod spec_support;
use serde_json::{Value, json};
use spec_support::{direct, parse, queue, refused, set};
#[test]
fn only_job_id_may_appear_in_a_path_and_only_where_a_job_exists() {
refused(set(queue(), "/flow/submit/call/path", json!("/images/{prompt}")), "flow.submit.call.path", "only {job_id} may be used in a path");
refused(set(queue(), "/flow/submit/call/path", json!("/images/{model}")), "flow.submit.call.path", "only {job_id} may be used in a path");
refused(set(queue(), "/flow/submit/call/path", json!("/images/{job_id}")), "flow.submit.call", "{job_id} is not available");
refused(set(direct(), "/flow/call/path", json!("/images/{job_id}")), "flow.call", "{job_id} is not available");
}
#[test]
fn a_placeholder_this_version_lacks_is_refused_by_name() {
refused(
set(queue(), "/flow/submit/call/body", json!({"seed": "{seed}", "p": "{prompt}"})),
"flow.submit.call.body",
"unsupported: placeholder {seed}",
);
refused(
set(queue(), "/flow/poll/call/query", json!({"id": "{job_id}", "x": "{param.size}"})),
"flow.poll.call.query",
"unsupported: placeholder {param.size}",
);
}
#[test]
fn a_body_key_cannot_be_a_template() {
refused(set(queue(), "/flow/submit/call/body", json!({"{prompt}": 1, "p": "{prompt}"})), "flow.submit.call.body", "a key cannot hold a brace");
}
#[test]
fn the_polling_and_cancel_calls_must_name_the_job() {
refused(set(queue(), "/flow/poll/call/query", json!({"id": "fixed"})), "flow.poll.call", "never uses {job_id}");
refused(set(queue(), "/flow/cancel/path", json!("/jobs")), "flow.cancel", "never uses {job_id}");
assert!(parse(&set(queue(), "/flow/cancel", Value::Null)).is_ok(), "cancel is optional");
}
#[test]
fn the_prompt_must_be_sent_and_every_model_must_require_it() {
refused(set(queue(), "/flow/submit/call/body", json!({"n": 1})), "flow", "the prompt is never sent");
refused(set(queue(), "/models/0/requires", json!([])), "models[0].requires", "needs every model to require a prompt");
}
#[test]
fn a_body_belongs_to_a_post_and_stays_small() {
refused(set(queue(), "/flow/poll/call/body", json!({"id": "{job_id}"})), "flow.poll.call.body", "only a POST has a body");
let pad = "x".repeat(4096);
refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": pad})), "flow.submit.call.body", "at most 4 KiB");
let fits = "x".repeat(4096 - r#"{"p":"{prompt}","pad":""}"#.len());
assert!(parse(&set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": fits}))).is_ok());
}
#[test]
fn query_values_are_few_plain_and_short() {
let q = |v: Value| set(queue(), "/flow/poll/call/query", v);
refused(q(json!({"bad name": "{job_id}"})), "flow.poll.call.query", "plain");
refused(q(json!({"id": "x".repeat(257)})), "flow.poll.call.query", "plain");
let nine: serde_json::Map<String, Value> = (0..9).map(|i| (format!("k{i}"), json!("{job_id}"))).collect();
refused(q(Value::Object(nine)), "flow.poll.call.query", "at most 8");
let eight: serde_json::Map<String, Value> = (0..8).map(|i| (format!("k{i}"), json!("{job_id}"))).collect();
assert!(parse(&q(Value::Object(eight))).is_ok());
}
#[test]
fn a_literal_brace_is_written_doubled() {
let body = json!({"p": "{prompt}", "note": "{{not a slot}}"});
assert!(parse(&set(queue(), "/flow/submit/call/body", body)).is_ok());
refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "note": "{oops"})), "flow.submit.call.body", "never closed");
}
+3 -143
View File
@@ -1,55 +1,10 @@
//! Rules a declarative spec must keep (task u2). Each case feeds an input that only the named rule
//! refuses, and checks where the error points and what it says.
mod spec_support;
use super::spec_support;
use craft_ai_core::spec::{MAX_SPEC_BYTES, Spec};
use serde_json::{Value, json};
use spec_support::{direct, parse, queue, refused, set};
#[test]
fn both_documented_shapes_are_accepted_and_round_trip() {
for v in [queue(), direct()] {
let spec = parse(&v).unwrap();
assert_eq!(Spec::parse(&serde_json::to_string(&spec).unwrap()).unwrap(), spec);
}
}
#[test]
fn the_file_size_limit_holds_at_its_edge() {
let text = queue().to_string();
let pad = MAX_SPEC_BYTES - text.len();
assert!(Spec::parse(&format!("{text}{}", " ".repeat(pad))).is_ok());
let e = Spec::parse(&format!("{text}{}", " ".repeat(pad + 1))).unwrap_err();
assert!(e.why.contains("too large"), "{e}");
}
#[test]
fn a_feature_this_version_lacks_is_refused_by_name_never_ignored() {
refused(set(queue(), "/flow/submit", json!({"webhook": "x"})), "spec", "webhook");
let mut v = queue();
v["streaming"] = json!(true);
refused(v, "spec", "streaming");
let mut v = queue();
v["models"][0]["params"] = json!(["seed"]);
refused(v, "spec", "params");
}
#[test]
fn only_version_one_is_read() {
refused(set(queue(), "/spec_version", json!(2)), "spec_version", "only version 1");
}
#[test]
fn the_base_address_follows_the_connection_rules() {
refused(set(queue(), "/base", json!("http://api.example.com")), "base", "plain http");
refused(set(queue(), "/base", json!("https://u:p@api.example.com")), "base", "user-info");
refused(set(queue(), "/base", json!("https://api.example.com/v2?x=1")), "base", "no query");
refused(set(queue(), "/base", json!("https://api.example.com/v2#top")), "base", "no query");
refused(set(queue(), "/base", json!("ftp://api.example.com")), "base", "http");
refused(set(queue(), "/base", json!("https://api.example.com/v2/../x")), "base", "'..'");
assert!(parse(&set(queue(), "/base", json!("https://api.example.com"))).is_ok());
}
use serde_json::json;
use spec_support::{parse, queue, refused, set};
#[test]
fn a_path_cannot_leave_the_base() {
@@ -70,98 +25,3 @@ fn a_path_cannot_leave_the_base() {
refused(path(&format!("/{}", "a".repeat(256))), at, "too long");
assert!(parse(&path(&format!("/{}", "a".repeat(255)))).is_ok());
}
#[test]
fn the_key_header_follows_the_connection_rules() {
let name = |n: &str| set(queue(), "/auth/name", json!(n));
refused(name("authorization"), "auth", "Authorization");
refused(name("host"), "auth", "cannot carry a key");
refused(name("proxy-x"), "auth", "network");
refused(name("bad name"), "auth", "letters, digits");
refused(name(""), "auth", "1 to 64");
assert!(parse(&set(queue(), "/auth", json!({"kind": "bearer"}))).is_ok());
assert!(parse(&set(queue(), "/auth", json!({"kind": "none"}))).is_ok());
}
#[test]
fn a_model_is_declared_completely_or_not_at_all() {
let m = |field: &str, to: Value| set(queue(), &format!("/models/0/{field}"), to);
refused(m("id", json!("bad id")), "models[0].id", "");
refused(m("capability", json!("nope")), "models[0].capability", "");
refused(m("label", json!(" ")), "models[0].label", "label");
refused(m("accepts", json!({})), "models[0].accepts", "at least one");
refused(m("accepts", json!({"prompt": 0})), "models[0].accepts", "must be 1");
refused(m("accepts", json!({"prompt": 2})), "models[0].accepts", "must be 1");
refused(m("accepts", json!({"source": 1})), "models[0].accepts", "unsupported: input 'source'");
refused(m("requires", json!(["source"])), "models[0].requires", "must also be accepted");
refused(m("max_outputs", json!(0)), "models[0].max_outputs", "1 to 4");
refused(m("max_outputs", json!(5)), "models[0].max_outputs", "1 to 4");
refused(set(queue(), "/models", json!([])), "models", "at least one");
let one = queue()["models"][0].clone();
refused(set(queue(), "/models", json!([one.clone(), one.clone()])), "models[1].id", "twice");
let many: Vec<Value> = (0..17).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect();
refused(set(queue(), "/models", json!(many)), "models", "at most 16");
let sixteen: Vec<Value> = (0..16).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect();
assert!(parse(&set(queue(), "/models", json!(sixteen))).is_ok());
}
#[test]
fn the_status_table_maps_words_to_the_four_states() {
let states = |v: Value| set(queue(), "/flow/poll/states", v);
let at = "flow.poll.states";
refused(states(json!({"Error": "failed"})), at, "succeeded");
refused(states(json!({"Ready": "succeeded"})), at, "failed");
refused(states(json!({})), at, "succeeded");
let table = |running: usize| {
let mut t = serde_json::Map::new();
for i in 0..running {
t.insert(format!("w{i}"), json!("running"));
}
t.insert("ok".into(), json!("succeeded"));
t.insert("bad".into(), json!("failed"));
Value::Object(t)
};
assert!(parse(&states(table(14))).is_ok(), "16 entries are allowed");
refused(states(table(15)), at, "at most 16");
}
#[test]
fn a_pointer_is_a_bounded_rfc_6901_path() {
let at = |p: &str| set(queue(), "/flow/poll/result/at", json!(p));
refused(at("result/sample"), "flow.poll.result.at", "starts with /");
refused(at("/a/b/c/d/e/f/g/h/i"), "flow.poll.result.at", "8 levels");
assert!(parse(&at("/a/b/c/d/e/f/g/h")).is_ok());
refused(set(queue(), "/flow/submit/job_id_at", json!("id")), "flow.submit.job_id_at", "starts with /");
refused(set(queue(), "/flow/poll/status_at", json!("")), "flow.poll.status_at", "starts with /");
}
#[test]
fn a_result_says_what_it_is() {
let ex = |v: Value| set(queue(), "/flow/poll/result", v);
refused(ex(json!({"at": "/x", "as": "url"})), "flow.poll.result", "media_type");
refused(ex(json!({"at": "/x", "as": "base64"})), "flow.poll.result", "media_type");
refused(ex(json!({"at": "/x", "as": "text", "media_type": "text/plain"})), "flow.poll.result", "text");
refused(ex(json!({"at": "/x", "as": "url", "media_type": "not a type"})), "flow.poll.result", "media_type");
assert!(parse(&ex(json!({"at": "/x", "as": "text"}))).is_ok());
}
#[test]
fn limits_are_bounded() {
let l = |field: &str, to: Value| {
let mut v = queue();
v["limits"] = json!({ field: to });
v
};
refused(l("max_polls", json!(0)), "limits.max_polls", "1 to 10000");
refused(l("max_polls", json!(10001)), "limits.max_polls", "1 to 10000");
refused(l("max_seconds", json!(0)), "limits.max_seconds", "1 to 3600");
refused(l("max_seconds", json!(3601)), "limits.max_seconds", "1 to 3600");
assert!(parse(&l("max_polls", json!(10000))).is_ok());
}
#[test]
fn the_probe_is_a_free_read() {
refused(set(queue(), "/probe/method", json!("POST")), "probe", "GET");
refused(set(queue(), "/probe/body", json!({"a": 1})), "probe", "only a POST has a body");
refused(set(queue(), "/probe/path", json!("/a/../b")), "probe.path", "'..'");
}
-13
View File
@@ -24,19 +24,6 @@ pub fn queue() -> Value {
})
}
pub fn direct() -> Value {
json!({
"spec_version": 1, "id": "plain-images", "label": "Plain Images",
"base": "http://127.0.0.1:8080",
"models": [{"id": "m", "label": "M", "capability": "image.generate",
"accepts": {"prompt": 1}, "requires": ["prompt"]}],
"flow": {"kind": "request_response",
"call": {"method": "POST", "path": "/images",
"body": {"model": "{model}", "prompt": "{prompt}"}},
"result": {"at": "/data/0/b64_json", "as": "base64", "media_type": "image/png"}}
})
}
/// Replaces the value at `pointer`, or adds it when the parent object lacks that key.
pub fn set(mut v: Value, pointer: &str, to: Value) -> Value {
let (parent, key) = pointer.rsplit_once('/').unwrap_or(("", pointer));
+1 -54
View File
@@ -1,32 +1,13 @@
//! Substitution rules for declarative specs: what a template may name, and that the structure of
//! a request can never come from the user's text.
use craft_ai_core::spec::template::{Slot, Values, render_text, render_value, slots, value_slots};
use craft_ai_core::spec::template::{Values, render_text, render_value};
use serde_json::json;
fn values() -> Values<'static> {
Values { prompt: Some("a red door"), model: Some("img-1"), job_id: Some("job-7") }
}
#[test]
fn the_three_names_are_known_and_nothing_else() {
assert_eq!(slots("{prompt} {model} {job_id}").unwrap(), vec![Slot::Prompt, Slot::Model, Slot::JobId]);
assert_eq!(slots("no slots here").unwrap(), vec![]);
for other in ["{seed}", "{param.size}", "{Prompt}", "{}", "{ prompt }"] {
let why = slots(other).unwrap_err();
assert!(why.contains("unsupported: placeholder"), "{other}: {why}");
}
assert_eq!(slots("{seed}").unwrap_err(), "unsupported: placeholder {seed}");
}
#[test]
fn braces_are_closed_or_doubled() {
assert!(slots("a { b").unwrap_err().contains("never closed"));
assert!(slots("a } b").unwrap_err().contains("lone }"));
assert_eq!(render_text("{{literal}}", &values()).unwrap(), "{literal}");
assert_eq!(render_text("{{{prompt}}}", &values()).unwrap(), "{a red door}");
}
#[test]
fn text_is_inserted_and_never_read_again() {
let v = Values { prompt: Some("{job_id} and {{ and }"), ..values() };
@@ -43,37 +24,3 @@ fn a_prompt_cannot_add_a_field_or_change_a_key() {
assert!(body.get("admin").is_none());
assert_eq!(body["n"], json!(1));
}
#[test]
fn keys_are_literal_and_nested_values_are_rendered() {
let template = json!({"a": [{"b": "{model}"}, "{job_id}"], "c": {"d": "{prompt}"}});
let body = render_value(&template, &values()).unwrap();
assert_eq!(body, json!({"a": [{"b": "img-1"}, "job-7"], "c": {"d": "a red door"}}));
assert_eq!(value_slots(&template).unwrap(), vec![Slot::Model, Slot::JobId, Slot::Prompt]);
assert!(value_slots(&json!({"{prompt}": 1})).unwrap_err().contains("key"));
}
#[test]
fn a_key_is_never_substituted_even_when_it_looks_like_a_slot() {
let body = render_value(&json!({"{prompt}": "{model}"}), &values()).unwrap();
assert_eq!(body, json!({"{prompt}": "img-1"}));
}
#[test]
fn a_slot_with_no_value_is_an_error_not_an_empty_string() {
let v = Values { prompt: Some("x"), ..Values::default() };
let why = render_text("/jobs/{job_id}", &v).unwrap_err();
assert!(why.contains("{job_id} is not available"), "{why}");
}
#[test]
fn repeated_slots_share_one_rendered_budget() {
let prompt = "x".repeat(64 * 1024);
let v = Values { prompt: Some(&prompt), ..values() };
let slots = vec![json!("{prompt}"); 16];
assert!(render_value(&json!({ "a": slots }), &v).is_ok());
let slots = vec![json!("{prompt}{prompt}{prompt}{prompt}"); 32];
let why = render_value(&json!({ "a": slots }), &v).unwrap_err();
assert!(why.contains("at most"), "{why}");
assert!(render_text(&"{prompt}".repeat(128), &v).is_err());
}
+4 -4
View File
@@ -19,10 +19,10 @@ dirs = "7"
sysinfo = "0.39"
ureq = { version = "3", features = ["json"] }
sha2 = "0.11"
candle-core = { version = "0.9", optional = true }
candle-nn = { version = "0.9", optional = true }
candle-transformers = { version = "0.9", optional = true }
tokenizers = { version = "0.22", optional = true, default-features = false, features = ["onig"] }
candle-core = { version = "0.11.1", optional = true }
candle-nn = { version = "0.11.1", optional = true }
candle-transformers = { version = "0.11.1", optional = true }
tokenizers = { version = "0.23", optional = true, default-features = false, features = ["onig"] }
[features]
# Local GGUF inference on candle. Heavy dependency tree; apps opt in.
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "craft-android-res"
description = "Bounded readers for compiled Android binary XML and resource tables"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
craft-testkit = { workspace = true }
+16
View File
@@ -0,0 +1,16 @@
# craft-android-res
Read-only wire decoding for Android compiled XML (AXML) and Android resource
tables (ARSC). XML and resource tables share the bounded chunk, string-pool,
and typed-value readers. APK container selection, manifest inventory policy,
device/security interpretation, and presentation remain consumer-owned.
## Provenance
The decoders, checked-reader subset, and synthetic test fixture subset were
moved from [Craft Anything at 8cec25d](https://github.com/storytold/craft-anything/tree/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/formats).
The original implementation is Brandon Thomas (echelon), [f64ae3bf](https://github.com/storytold/craft-anything/commit/f64ae3bf3c8863a982af1304e06de20653803968).
Later parser bounds and resource identity/qualifier work came from Afloat
and BFlat; typed-attribute handling also includes RRFZ's work. The original
[fixture generator](https://github.com/storytold/craft-anything/blob/8cec25d02007db604b57ce6735ad4eb44a1a9948/crates/testkit/src/android.rs)
remains the source of the test data. No external assets or added dependencies.
+881
View File
@@ -0,0 +1,881 @@
//! Android compiled resource tables (`resources.arsc`): the global string pool, packages, type
//! and key string pools, type specs, and typed entries per configuration (locale, density,
//! orientation, SDK level…). Simple and complex (bag) entries, sparse and 16-bit offset tables.
use crate::Error;
use crate::axml::{MAX_RETAINED_VALUE_BYTES, ResValue, StringPool, ValueBudget, chunk, report_partial_string_pool};
use crate::bytes::Reader;
use serde::Serialize;
const RES_TABLE: u16 = 0x0002;
const RES_PACKAGE: u16 = 0x0200;
const RES_TYPE: u16 = 0x0201;
const RES_TYPE_SPEC: u16 = 0x0202;
const RES_LIBRARY: u16 = 0x0203;
const NO_ENTRY: u32 = 0xffff_ffff;
const MAX_PACKAGES: usize = 64;
const MAX_BAG: usize = 4096;
/// Limits for one table.
#[derive(Debug, Clone, Copy)]
pub struct Limits {
/// Most entries decoded across all types and configurations.
pub max_entries: usize,
/// Most bytes retained in formatted simple-entry and bag values.
pub max_value_bytes: usize,
}
impl Default for Limits {
fn default() -> Self {
Limits { max_entries: 2_000_000, max_value_bytes: MAX_RETAINED_VALUE_BYTES }
}
}
const VALUE_BUDGET_WARNING: &str = "resource value budget reached; remaining values were omitted";
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct TypeInfo {
pub id: u8,
pub name: String,
pub entry_count: u32,
/// Configuration qualifiers that have values for this type ("default" for none).
pub configs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Package {
pub id: u32,
pub name: String,
pub types: Vec<TypeInfo>,
pub keys: usize,
/// Shared-library package references (id → name).
pub libraries: Vec<(u32, String)>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BagItem {
pub name: String,
pub value: String,
pub value_type: &'static str,
}
/// One value of one resource in one configuration.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Entry {
/// `0xPPTTEEEE`
pub id: String,
pub package: String,
#[serde(rename = "type")]
pub type_name: String,
pub key: String,
/// Qualifier string, e.g. `fr`, `es-rMX`, `night-xhdpi`, or `default`.
pub config: String,
/// Android locale qualifier, empty for the default locale.
pub locale: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub value_type: Option<&'static str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub bag: Vec<BagItem>,
#[serde(skip)]
pub raw: Option<ResValue>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Table {
pub packages: Vec<Package>,
pub global_strings: usize,
pub entries: Vec<Entry>,
pub truncated: bool,
pub warnings: Vec<String>,
}
fn utf16_fixed(r: &Reader<'_>, off: usize, chars: usize) -> String {
let units: Vec<u16> = (0..chars).map_while(|i| r.u16_le(off + i * 2)).take_while(|&u| u != 0).collect();
String::from_utf16_lossy(&units)
}
fn ascii2(b: &[u8]) -> String {
b.iter().take_while(|&&c| c != 0).map(|&c| if c.is_ascii_graphic() { c as char } else { '?' }).collect()
}
/// A packed 2-byte language or region code (3-letter codes are packed into 15 bits).
fn unpack_code(b: &[u8], base: u8) -> String {
let (b0, b1) = (b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0));
if b0 & 0x80 != 0 {
let first = b1 & 0x1f;
let second = ((b1 & 0xe0) >> 5) | ((b0 & 0x03) << 3);
let third = (b0 & 0x7c) >> 2;
[first, second, third].iter().map(|c| (c.wrapping_add(base)) as char).collect()
} else {
ascii2(&[b0, b1])
}
}
fn locale_qualifier(r: &Reader<'_>, off: usize, size: usize, get8: impl Fn(usize) -> Option<u8>) -> String {
let lang = if size >= 12 { r.slice(off + 8, 2).map(|b| unpack_code(b, b'a')).unwrap_or_default() } else { String::new() };
let region = if size >= 12 { r.slice(off + 10, 2).map(|b| unpack_code(b, b'0')).unwrap_or_default() } else { String::new() };
// Extended locale fields were appended to ResTable_config. Older
// configurations end before one or more of these fields.
let subtag = |start: usize, len: usize| {
if start + len <= size { r.slice(off + start, len).map(ascii2).unwrap_or_default() } else { String::new() }
};
let script = if get8(52).unwrap_or(0) == 0 { subtag(36, 4) } else { String::new() };
let variant = subtag(40, 8);
let numbering = subtag(53, 8);
let mut locale = lang;
if !locale.is_empty() && (!script.is_empty() || !variant.is_empty() || !numbering.is_empty()) {
locale.insert_str(0, "b+");
for part in [&script, &region, &variant].into_iter().filter(|p| !p.is_empty()) {
locale.push('+');
locale.push_str(part);
}
if !numbering.is_empty() {
locale.push_str("+u+nu+");
locale.push_str(&numbering);
}
} else if !locale.is_empty() && !region.is_empty() {
locale.push_str(&format!("-r{region}"));
}
locale
}
/// Qualifier string and locale for a `ResTable_config` at `off`.
fn config_qualifiers(r: &Reader<'_>, off: usize) -> (String, String) {
let size = r.u32_le(off).unwrap_or(0) as usize;
let get8 = |o: usize| if o < size { r.u8(off + o) } else { None };
let get16 = |o: usize| if o + 1 < size { r.u16_le(off + o) } else { None };
let mut q: Vec<String> = Vec::new();
if let Some(mcc) = get16(4).filter(|&v| v != 0) {
q.push(format!("mcc{mcc}"));
}
if let Some(mnc) = get16(6).filter(|&v| v != 0) {
q.push(format!("mnc{}", if mnc == u16::MAX { 0 } else { mnc }));
}
let locale = locale_qualifier(r, off, size, get8);
if !locale.is_empty() {
q.push(locale.clone());
}
let axis = |q: &mut Vec<String>, v: Option<u8>, mask, names: &[(u8, &str)]| {
if let Some(key) = v.map(|n| n & mask)
&& let Some((_, name)) = names.iter().find(|(value, _)| *value == key)
{
q.push((*name).to_owned());
}
};
axis(&mut q, get8(19), 0x03, &[(1, "neuter"), (2, "feminine"), (3, "masculine")]);
if let Some(sl) = get8(28) {
match sl & 0xc0 {
0x40 => q.push("ldltr".into()),
0x80 => q.push("ldrtl".into()),
_ => {}
}
}
if let Some(sw) = get16(30).filter(|&v| v != 0) {
q.push(format!("sw{sw}dp"));
}
if let Some(w) = get16(32).filter(|&v| v != 0) {
q.push(format!("w{w}dp"));
}
if let Some(h) = get16(34).filter(|&v| v != 0) {
q.push(format!("h{h}dp"));
}
if let Some(sl) = get8(28) {
match sl & 0x0f {
1 => q.push("small".into()),
2 => q.push("normal".into()),
3 => q.push("large".into()),
4 => q.push("xlarge".into()),
_ => {}
}
match sl & 0x30 {
0x10 => q.push("notlong".into()),
0x20 => q.push("long".into()),
_ => {}
}
}
axis(&mut q, get8(48), 0x03, &[(1, "notround"), (2, "round")]);
axis(&mut q, get8(49), 0x03, &[(1, "nowidecg"), (2, "widecg")]);
axis(&mut q, get8(49), 0x0c, &[(4, "lowdr"), (8, "highdr")]);
match get8(12) {
Some(1) => q.push("port".into()),
Some(2) => q.push("land".into()),
Some(3) => q.push("square".into()),
_ => {}
}
if let Some(ui) = get8(29) {
match ui & 0x0f {
2 => q.push("desk".into()),
3 => q.push("car".into()),
4 => q.push("television".into()),
5 => q.push("appliance".into()),
6 => q.push("watch".into()),
7 => q.push("vrheadset".into()),
_ => {}
}
match ui & 0x30 {
0x10 => q.push("notnight".into()),
0x20 => q.push("night".into()),
_ => {}
}
}
if let Some(d) = get16(14).filter(|&v| v != 0) {
q.push(match d {
120 => "ldpi".into(),
160 => "mdpi".into(),
213 => "tvdpi".into(),
240 => "hdpi".into(),
320 => "xhdpi".into(),
480 => "xxhdpi".into(),
640 => "xxxhdpi".into(),
0xfffe => "anydpi".into(),
0xffff => "nodpi".into(),
d => format!("{d}dpi"),
});
}
match get8(13) {
Some(1) => q.push("notouch".into()),
Some(3) => q.push("finger".into()),
_ => {}
}
axis(&mut q, get8(18), 0x03, &[(1, "keysexposed"), (2, "keyshidden"), (3, "keyssoft")]);
match get8(16) {
Some(1) => q.push("nokeys".into()),
Some(2) => q.push("qwerty".into()),
Some(3) => q.push("12key".into()),
_ => {}
}
axis(&mut q, get8(18), 0x0c, &[(4, "navexposed"), (8, "navhidden")]);
match get8(17) {
Some(1) => q.push("nonav".into()),
Some(2) => q.push("dpad".into()),
Some(3) => q.push("trackball".into()),
Some(4) => q.push("wheel".into()),
_ => {}
}
if let (Some(w), Some(h)) = (get16(20), get16(22))
&& w != 0
&& h != 0
{
q.push(format!("{w}x{h}"));
}
if let Some(v) = get16(24).filter(|&v| v != 0) {
q.push(format!("v{v}"));
}
let s = if q.is_empty() { "default".to_string() } else { q.join("-") };
(s, locale)
}
/// A type's configuration is part of its header, not the entry offsets or payload.
fn type_config(r: &Reader<'_>, at: usize, header_size: usize) -> Option<(String, String)> {
let config = Reader::new(r.slice(at.checked_add(20)?, header_size.checked_sub(20)?)?);
let size = config.u32_le(0)? as usize;
if size < 4 || config.slice(0, size).is_none() {
return None;
}
Some(config_qualifiers(&config, 0))
}
struct Pkg<'a> {
name: &'a str,
id: u32,
types: &'a StringPool,
keys: &'a StringPool,
}
fn type_name(p: &Pkg<'_>, id: u8) -> String {
p.types.get(u32::from(id).wrapping_sub(1)).map(str::to_string).unwrap_or_else(|| format!("type{id}"))
}
/// Parse a resource table.
pub fn parse(data: &[u8], limits: Limits) -> Result<Table, Error> {
let r = Reader::new(data);
let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("resource table header".into()))?;
if t != RES_TABLE {
return Err(Error::Malformed(format!("not a resource table (chunk type {t:#x})")));
}
if h < 12 {
return Err(Error::Truncated("resource table header".into()));
}
let data = data.get(..size).ok_or_else(|| Error::Truncated("resource table payload".into()))?;
let r = Reader::new(data);
let mut table = Table::default();
let mut global = StringPool::default();
let mut value_budget = ValueBudget::new(limits.max_value_bytes);
let mut pos = h;
while pos < size {
let Some((ct, _ch, cs)) = chunk(&r, pos) else {
table.truncated = true;
table.warnings.push(format!("unreadable chunk at offset {pos}"));
break;
};
match ct {
crate::axml::RES_STRING_POOL => match StringPool::parse(data, pos) {
Ok(p) => {
report_partial_string_pool(&p, "global string pool", &mut table.truncated, &mut table.warnings);
table.global_strings = p.declared;
global = p;
}
Err(e) => {
table.truncated = true;
table.warnings.push(format!("global string pool: {e}"));
}
},
RES_PACKAGE => {
if table.packages.len() >= MAX_PACKAGES {
table.truncated = true;
table.warnings.push("too many packages; the rest were skipped".into());
} else {
parse_package(data, pos, cs, &global, &mut table, limits, &mut value_budget);
}
}
_ => {}
}
pos = match pos.checked_add(cs) {
Some(p) => p,
None => break,
};
}
Ok(table)
}
fn parse_package(data: &[u8], pos: usize, cs: usize, global: &StringPool, table: &mut Table, limits: Limits, value_budget: &mut ValueBudget) {
let Some(data) = pos.checked_add(cs).and_then(|end| data.get(..end)) else {
table.truncated = true;
table.warnings.push("package runs past its resource table".into());
return;
};
let r = Reader::new(data);
let hsize = usize::from(r.u16_le(pos + 2).unwrap_or(0));
if hsize < 284 {
table.truncated = true;
table.warnings.push(format!("package at offset {pos}: incomplete header"));
return;
}
let id = r.u32_le(pos + 8).unwrap_or(0);
let name = utf16_fixed(&r, pos + 12, 128);
// Older 284-byte packages predate this field. Type names still use the
// unshifted chunk ID, while public resource identities include the offset.
let type_id_offset = if hsize >= 288 { r.u32_le(pos + 284).unwrap_or(0) } else { 0 };
let Ok(type_id_offset) = u8::try_from(type_id_offset) else {
table.truncated = true;
table.warnings.push(format!("package {name}: type ID offset is outside the one-byte type field"));
return;
};
let type_strings = r.u32_le(pos + 268).unwrap_or(0) as usize;
let key_strings = r.u32_le(pos + 276).unwrap_or(0) as usize;
let end = data.len();
let mut read_pool = |offset: usize, label: &str| {
if offset == 0 {
return StringPool::default();
}
let Some(start) = pos.checked_add(offset).filter(|&start| offset >= hsize && start < end) else {
table.truncated = true;
table.warnings.push(format!("package {name}: {label} string pool is outside its payload"));
return StringPool::default();
};
match StringPool::parse(data, start) {
Ok(pool) => {
report_partial_string_pool(&pool, &format!("package {name}: {label} string pool"), &mut table.truncated, &mut table.warnings);
pool
}
Err(error) => {
table.truncated = true;
table.warnings.push(format!("package {name}: {label} string pool: {error}"));
StringPool::default()
}
}
};
let types = read_pool(type_strings, "type");
let keys = read_pool(key_strings, "key");
let mut package = Package { id, name: name.clone(), types: Vec::new(), keys: keys.declared, libraries: Vec::new() };
let p = Pkg { name: &name, id, types: &types, keys: &keys };
let mut c = pos.saturating_add(hsize.max(8));
while c < end {
let Some((ct, ch, sz)) = chunk(&r, c) else {
table.truncated = true;
table.warnings.push(format!("package {name}: unreadable chunk at offset {c}"));
break;
};
// Each child was checked against its package; reads within it must also stop before
// the next sibling, including fixed-width library records and bag headers.
let Some(child) = data.get(..c.saturating_add(sz)) else {
table.truncated = true;
table.warnings.push(format!("package {name}: child chunk runs past its package"));
break;
};
let r = Reader::new(child);
let local_tid = r.u8(c + 8).unwrap_or(0);
let type_id = local_tid.checked_add(type_id_offset).filter(|_| local_tid != 0);
match (ct, type_id) {
(RES_TYPE_SPEC, Some(tid)) if ch >= 16 => {
let count = r.u32_le(c + 12).unwrap_or(0);
if !package.types.iter().any(|t| t.id == tid) && package.types.len() < 256 {
package.types.push(TypeInfo { id: tid, name: type_name(&p, local_tid), entry_count: count, configs: Vec::new() });
}
}
(RES_TYPE, Some(tid)) if ch >= 24 => {
let Some((cfg, locale)) = type_config(&r, c, ch) else {
table.truncated = true;
table.warnings.push(format!("package {name}: incomplete type configuration at offset {c}"));
// The child extent was already validated by chunk().
c += sz;
continue;
};
match package.types.iter_mut().find(|t| t.id == tid) {
Some(t) => {
if !t.configs.contains(&cfg) && t.configs.len() < 4096 {
t.configs.push(cfg.clone());
}
}
None => {
if package.types.len() < 256 {
package.types.push(TypeInfo {
id: tid,
name: type_name(&p, local_tid),
entry_count: r.u32_le(c + 12).unwrap_or(0),
configs: vec![cfg.clone()],
})
}
}
}
parse_type(&r, c, (ch, sz), (cfg, locale), &p, tid, global, table, limits, value_budget);
}
(RES_TYPE_SPEC | RES_TYPE, None) if ch >= 16 => {
table.truncated = true;
table.warnings.push(format!("package {name}: type ID {local_tid} with offset {type_id_offset} is outside the one-byte type field"));
}
(RES_LIBRARY, _) if ch >= 12 => {
let n = r.u32_le(c + 8).unwrap_or(0) as usize;
let available = (sz - ch) / 260;
if n > available {
table.warnings.push(format!("package {name}: library records run past their chunk"));
}
if n > available.min(256) {
table.truncated = true;
}
for i in 0..n.min(256).min(available) {
let e = c + ch + i * 260;
if let Some(lid) = r.u32_le(e) {
package.libraries.push((lid, utf16_fixed(&r, e + 4, 128)));
}
}
}
(RES_TYPE_SPEC | RES_TYPE | RES_LIBRARY, _) => {
table.truncated = true;
table.warnings.push(format!("package {name}: incomplete chunk header at offset {c}"));
}
_ => {}
}
c = match c.checked_add(sz) {
Some(x) => x,
None => break,
};
}
table.packages.push(package);
}
#[allow(clippy::too_many_arguments)]
fn parse_type(
r: &Reader<'_>,
c: usize,
(ch, sz): (usize, usize),
(cfg, locale): (String, String),
p: &Pkg<'_>,
type_id: u8,
global: &StringPool,
table: &mut Table,
limits: Limits,
value_budget: &mut ValueBudget,
) {
let tid = r.u8(c + 8).unwrap_or(0);
let flags = r.u8(c + 9).unwrap_or(0);
let count = r.u32_le(c + 12).unwrap_or(0) as usize;
let entries_start = r.u32_le(c + 16).unwrap_or(0) as usize;
let end = c + sz;
let tname = type_name(p, tid);
let sparse = flags & 0x01 != 0;
let off16 = flags & 0x02 != 0;
// (entry index, offset from entries_start)
let mut slots: Vec<(u32, usize)> = Vec::new();
let table_bytes = if sparse || off16 { count.saturating_mul(if sparse { 4 } else { 2 }) } else { count.saturating_mul(4) };
if c.saturating_add(ch).saturating_add(table_bytes) > end {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): entry table runs past its chunk"));
return;
}
if count != 0 && (entries_start < ch.saturating_add(table_bytes) || entries_start > sz) {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): invalid entry data start"));
return;
}
for i in 0..count {
let at = c + ch;
if sparse {
let (Some(idx), Some(o)) = (r.u16_le(at + i * 4), r.u16_le(at + i * 4 + 2)) else { break };
slots.push((u32::from(idx), usize::from(o) * 4));
} else if off16 {
let Some(o) = r.u16_le(at + i * 2) else { break };
if o != 0xffff {
slots.push((i as u32, usize::from(o) * 4));
}
} else {
let Some(o) = r.u32_le(at + i * 4) else { break };
if o != NO_ENTRY {
slots.push((i as u32, o as usize));
}
}
}
let mut skipped = 0usize;
for (idx, o) in slots {
if table.entries.len() >= limits.max_entries {
table.truncated = true;
break;
}
let Some(e) = c.checked_add(entries_start).and_then(|x| x.checked_add(o)).filter(|e| e.saturating_add(8) <= end) else {
skipped += 1;
continue;
};
let esize = usize::from(r.u16_le(e).unwrap_or(0));
let eflags = r.u16_le(e + 2).unwrap_or(0);
let id = (p.id << 24) | (u32::from(type_id) << 16) | (idx & 0xffff);
let mut entry = Entry {
id: format!("{id:#010x}"),
package: p.name.to_string(),
type_name: tname.clone(),
key: String::new(),
config: cfg.clone(),
locale: locale.clone(),
value: None,
value_type: None,
parent: None,
bag: Vec::new(),
raw: None,
};
if eflags & 0x08 != 0 {
// Compact entry: key index in the size field, type in the high byte of flags.
entry.key = p.keys.get(u32::from(r.u16_le(e).unwrap_or(0))).unwrap_or("").to_string();
let v = ResValue { data_type: (eflags >> 8) as u8, data: r.u32_le(e + 4).unwrap_or(0) };
entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING);
entry.value_type = Some(v.type_name());
entry.raw = Some(v);
} else {
entry.key = r.u32_le(e + 4).and_then(|k| p.keys.get(k)).unwrap_or("").to_string();
if eflags & 0x01 != 0 {
if esize < 16 || e.saturating_add(esize) > end {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): incomplete bag header"));
table.entries.push(entry);
continue;
}
let n = r.u32_le(e + 12).unwrap_or(0) as usize;
let mut m = e + esize;
if n > (end - m) / 12 {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): incomplete bag data"));
table.entries.push(entry);
continue;
}
let parent = r.u32_le(e + 8).unwrap_or(0);
if parent != 0 {
entry.parent = Some(format!("@{parent:#010x}"));
}
if n > MAX_BAG {
table.truncated = true;
}
for _ in 0..n.min(MAX_BAG) {
if m.saturating_add(12) > end {
break;
}
let name = r.u32_le(m).unwrap_or(0);
let v = ResValue { data_type: r.u8(m + 7).unwrap_or(0), data: r.u32_le(m + 8).unwrap_or(0) };
let value =
value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING).unwrap_or_default();
entry.bag.push(BagItem { name: format!("@{name:#010x}"), value, value_type: v.type_name() });
m += 12;
}
} else {
let v_at = e.saturating_add(esize.max(8));
if v_at.saturating_add(8) <= end {
let v = ResValue { data_type: r.u8(v_at + 3).unwrap_or(0), data: r.u32_le(v_at + 4).unwrap_or(0) };
entry.value = value_budget.take(v.format(global), &mut table.truncated, &mut table.warnings, VALUE_BUDGET_WARNING);
entry.value_type = Some(v.type_name());
entry.raw = Some(v);
} else {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): incomplete value"));
}
}
}
table.entries.push(entry);
}
if skipped > 0 {
table.truncated = true;
table.warnings.push(format!("{tname} ({cfg}): {skipped} entries run past their chunk"));
}
}
impl Table {
/// String resources grouped by locale (`""` = default): (locale, key, value).
pub fn strings_by_locale(&self) -> std::collections::BTreeMap<String, Vec<(String, String)>> {
let mut out: std::collections::BTreeMap<String, Vec<(String, String)>> = Default::default();
for e in self.entries.iter().filter(|e| e.type_name == "string") {
if let Some(v) = &e.value {
out.entry(e.locale.clone()).or_default().push((e.key.clone(), v.clone()));
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fixtures as fx;
#[test]
fn incomplete_table_prefix_is_rejected() {
let bytes = fx::resources_arsc();
assert!(matches!(parse(&bytes[..7], Limits::default()), Err(Error::Truncated(_))));
}
#[test]
fn decodes_table() {
let t = parse(&fx::resources_arsc(), Limits::default()).unwrap();
assert!(t.warnings.is_empty(), "{:?}", t.warnings);
assert_eq!(t.packages.len(), 1);
let p = &t.packages[0];
assert_eq!(p.id, 0x7f);
assert_eq!(p.name, fx::PACKAGE);
assert_eq!(p.types[0].name, "string");
assert_eq!(p.types[0].configs, vec!["default", "fr"]);
let by = t.strings_by_locale();
assert_eq!(by[""], vec![("app_name".to_string(), "Notes".to_string()), ("greeting".to_string(), "Hello".to_string())]);
assert_eq!(by["fr"], vec![("app_name".to_string(), "Notes FR".to_string()), ("greeting".to_string(), "Bonjour".to_string())]);
let app = t.entries.iter().find(|e| e.key == "app_name" && e.locale.is_empty()).unwrap();
assert_eq!(app.id, "0x7f010000");
let style = t.entries.iter().find(|e| e.type_name == "style").unwrap();
assert_eq!(style.key, "AppTheme");
assert_eq!(style.parent.as_deref(), Some("@0x01030005"));
assert_eq!(style.bag[0].value, "#ff336699");
assert_eq!(style.config, "night-xhdpi-v21");
}
#[test]
fn skipped_type_chunks_and_entries_mark_the_table_partial() {
let bytes = fx::resources_arsc();
// The French type chunk: RES_TYPE, an 84-byte header, and "fr" in its configuration.
let fr = (0..bytes.len() - 30).find(|&i| bytes[i..i + 4] == [0x01, 0x02, 84, 0] && &bytes[i + 28..i + 30] == b"fr").unwrap();
let corrupt = |at: usize, value: u32| {
let mut b = bytes.clone();
b[at..at + 4].copy_from_slice(&value.to_le_bytes());
parse(&b, Limits::default()).unwrap()
};
for (what, t) in [
("entry table past its chunk", corrupt(fr + 12, 1000)),
("invalid entry data start", corrupt(fr + 16, 0xffff)),
("an entry past its chunk", corrupt(fr + 84, 0x1000)),
// The second entry's header fits, but its value runs past the chunk.
("a value past its chunk", corrupt(fr + 88, 24)),
] {
let french = t.entries.iter().filter(|e| e.locale == "fr" && e.value.is_some()).count();
assert!(french < 2, "{what}: the corruption should lose a French value");
assert!(t.truncated, "{what}: lost content must mark the table partial");
assert!(!t.warnings.is_empty(), "{what}: lost content must be reported");
}
}
#[test]
fn distinct_locale_scripts_and_variants_keep_separate_keys() {
let mut cfg = [0u8; 64];
cfg[0] = 64;
cfg[8..12].copy_from_slice(b"zhTW");
cfg[36..40].copy_from_slice(b"Hant");
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hant+TW");
cfg[36..40].copy_from_slice(b"Hans");
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+Hans+TW");
cfg[52] = 1; // The inferred script is not part of the requested locale.
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW");
cfg[40..45].copy_from_slice(b"POSIX");
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX");
cfg[53..57].copy_from_slice(b"latn");
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "b+zh+TW+POSIX+u+nu+latn");
cfg[0] = 36; // Bytes beyond the declared configuration are unrelated.
assert_eq!(config_qualifiers(&Reader::new(&cfg), 0).1, "zh-rTW");
}
#[test]
fn qualifiers() {
let mut cfg = vec![0u8; 64];
cfg[0] = 64;
cfg[8] = b'e';
cfg[9] = b's';
cfg[10] = b'M';
cfg[11] = b'X';
cfg[12] = 2;
let (q, l) = config_qualifiers(&Reader::new(&cfg), 0);
assert_eq!(q, "es-rMX-land");
assert_eq!(l, "es-rMX");
}
fn le_u16(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_le_bytes());
}
fn le_u32(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_le_bytes());
}
fn type_spec(id: u8, entries: u32) -> Vec<u8> {
let mut c = Vec::new();
le_u16(&mut c, 0x0202);
le_u16(&mut c, 16);
le_u32(&mut c, 16 + 4 * entries);
c.push(id);
c.push(0);
le_u16(&mut c, 0);
le_u32(&mut c, entries);
for _ in 0..entries {
le_u32(&mut c, 0);
}
c
}
fn type_chunk(id: u8, entries: &[Vec<u8>]) -> Vec<u8> {
let mut cfg = vec![0u8; 64];
cfg[0] = 64;
let header = 20 + cfg.len();
let start = header + 4 * entries.len();
let mut body = Vec::new();
let mut offs = Vec::new();
for e in entries {
offs.push(body.len() as u32);
body.extend_from_slice(e);
}
let mut c = Vec::new();
le_u16(&mut c, 0x0201);
le_u16(&mut c, header as u16);
le_u32(&mut c, (start + body.len()) as u32);
c.push(id);
c.push(0);
le_u16(&mut c, 0);
le_u32(&mut c, entries.len() as u32);
le_u32(&mut c, start as u32);
c.extend_from_slice(&cfg);
for o in offs {
le_u32(&mut c, o);
}
c.extend(body);
c
}
fn table_with_entries(pool: &[&str], type_name: &str, keys: &[&str], entries: &[Vec<u8>]) -> Vec<u8> {
let global = fx::string_pool(pool, true);
let types = fx::string_pool(&[type_name], false);
let key_pool = fx::string_pool(keys, false);
let mut chunks = type_spec(1, entries.len() as u32);
chunks.extend(type_chunk(1, entries));
let header = 288usize;
let mut pkg = Vec::new();
le_u16(&mut pkg, 0x0200);
le_u16(&mut pkg, header as u16);
le_u32(&mut pkg, (header + types.len() + key_pool.len() + chunks.len()) as u32);
le_u32(&mut pkg, 0x7f);
pkg.extend(vec![0u8; 256]);
le_u32(&mut pkg, header as u32);
le_u32(&mut pkg, 1);
le_u32(&mut pkg, (header + types.len()) as u32);
le_u32(&mut pkg, keys.len() as u32);
le_u32(&mut pkg, 0);
pkg.extend(types);
pkg.extend(key_pool);
pkg.extend(chunks);
let mut out = Vec::new();
le_u16(&mut out, 0x0002);
le_u16(&mut out, 12);
le_u32(&mut out, (12 + global.len() + pkg.len()) as u32);
le_u32(&mut out, 1);
out.extend(global);
out.extend(pkg);
out
}
fn simple_string_entry(key: u32, pool_index: u32) -> Vec<u8> {
let mut e = Vec::new();
le_u16(&mut e, 8);
le_u16(&mut e, 0);
le_u32(&mut e, key);
le_u16(&mut e, 8);
e.push(0);
e.push(0x03);
le_u32(&mut e, pool_index);
e
}
fn compact_string_entry(key: u16, pool_index: u32) -> Vec<u8> {
let mut e = Vec::new();
le_u16(&mut e, key);
le_u16(&mut e, 0x0308);
le_u32(&mut e, pool_index);
e
}
fn bag_string_entry(key: u32, pool_indices: &[u32]) -> Vec<u8> {
let mut e = Vec::new();
le_u16(&mut e, 16);
le_u16(&mut e, 1);
le_u32(&mut e, key);
le_u32(&mut e, 0);
le_u32(&mut e, pool_indices.len() as u32);
for (i, idx) in pool_indices.iter().enumerate() {
le_u32(&mut e, 0x0101_0000 + i as u32);
le_u16(&mut e, 8);
e.push(0);
e.push(0x03);
le_u32(&mut e, *idx);
}
e
}
#[test]
fn value_budget_omits_long_copies_and_keeps_a_later_short_value() {
let long = "x".repeat(16);
let tight = Limits { max_value_bytes: 20, ..Limits::default() };
let keys = ["a", "b", "c"];
let simple =
table_with_entries(&[&long, "ok"], "string", &keys, &[simple_string_entry(0, 0), simple_string_entry(1, 0), simple_string_entry(2, 1)]);
let complete = parse(&simple, Limits::default()).unwrap();
assert!(!complete.truncated, "{:?}", complete.warnings);
assert_eq!(complete.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), Some(long.as_str()), Some("ok")]);
let partial = parse(&simple, tight).unwrap();
assert!(partial.truncated);
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), None, Some("ok")]);
let compact = table_with_entries(
&[&long, "ok"],
"string",
&keys,
&[compact_string_entry(0, 0), compact_string_entry(1, 0), compact_string_entry(2, 1)],
);
let partial = parse(&compact, tight).unwrap();
assert!(partial.truncated);
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
assert_eq!(partial.entries.iter().map(|e| e.value.as_deref()).collect::<Vec<_>>(), [Some(long.as_str()), None, Some("ok")]);
let bag = table_with_entries(&[&long, "ok"], "style", &["theme"], &[bag_string_entry(0, &[0, 0, 1])]);
let complete = parse(&bag, Limits::default()).unwrap();
assert!(!complete.truncated, "{:?}", complete.warnings);
assert_eq!(complete.entries[0].bag.iter().map(|i| i.value.as_str()).collect::<Vec<_>>(), [long.as_str(), long.as_str(), "ok"]);
let partial = parse(&bag, tight).unwrap();
assert!(partial.truncated);
assert!(partial.warnings.iter().any(|w| w.contains("value budget")), "{:?}", partial.warnings);
assert_eq!(partial.entries[0].bag.iter().map(|i| i.value.as_str()).collect::<Vec<_>>(), [long.as_str(), "", "ok"]);
}
}
+928
View File
@@ -0,0 +1,928 @@
//! Android binary XML (AXML): the compiled form of `AndroidManifest.xml` and `res/*.xml`.
//! Chunks, the string pool (UTF-8 and UTF-16), the resource-id map, namespaces, elements and
//! typed attribute values. Also the string pool and typed-value formatting that resource tables
//! share. Manifest inventory and policy are left to callers.
use crate::Error;
use crate::bytes::Reader;
use serde::Serialize;
pub const RES_STRING_POOL: u16 = 0x0001;
pub const RES_XML: u16 = 0x0003;
const XML_START_NS: u16 = 0x0100;
const XML_END_NS: u16 = 0x0101;
const XML_START_ELEMENT: u16 = 0x0102;
const XML_END_ELEMENT: u16 = 0x0103;
const XML_CDATA: u16 = 0x0104;
const XML_RESOURCE_MAP: u16 = 0x0180;
/// Most strings decoded from one pool.
const MAX_STRINGS: usize = 1_000_000;
/// Longest string kept (characters).
const MAX_STRING: usize = 64 * 1024;
/// Default budget for copied resource and XML values, and the base string-pool byte cap.
pub(crate) const MAX_RETAINED_VALUE_BYTES: usize = 64 << 20;
/// Base budget for decoded string bytes; larger chunks allow at most three times their size.
const BASE_POOL_BYTES: usize = MAX_RETAINED_VALUE_BYTES;
/// Most extra UTF-8 length candidates examined across one string pool.
const MAX_RECOVERY_PROBES: usize = 65_536;
/// Most XML nodes decoded.
const MAX_NODES: usize = 200_000;
/// Deepest element nesting tracked.
const MAX_DEPTH: usize = 512;
pub const ANDROID_NS: &str = "http://schemas.android.com/apk/res/android";
/// A chunk header: type, header size, total size, at `off`.
pub(crate) fn chunk(r: &Reader<'_>, off: usize) -> Option<(u16, usize, usize)> {
let t = r.u16_le(off)?;
let h = usize::from(r.u16_le(off.checked_add(2)?)?);
let s = r.u32_le(off.checked_add(4)?)? as usize;
if h < 8 || s < h || off.checked_add(s)? > r.len() {
return None;
}
Some((t, h, s))
}
/// Reads the bounded Android chunk header at the given byte offset.
pub fn chunk_header(data: &[u8], off: usize) -> Option<(u16, usize, usize)> {
chunk(&Reader::new(data), off)
}
/// A decoded string pool.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StringPool {
pub strings: Vec<String>,
pub utf8: bool,
/// Strings the pool declared (may exceed `strings.len()` when capped).
pub declared: usize,
/// Entries left empty because the UTF-8 recovery probe budget ran out.
pub recovery_omitted: usize,
}
impl StringPool {
pub fn get(&self, i: u32) -> Option<&str> {
if i == u32::MAX {
return None;
}
self.strings.get(i as usize).map(String::as_str)
}
/// Parse the pool whose chunk starts at `off`, retaining a prefix within the string and byte budgets.
pub fn parse(data: &[u8], off: usize) -> Result<StringPool, Error> {
let mut recovery_left = MAX_RECOVERY_PROBES;
Self::parse_with_recovery_budget(data, off, &mut recovery_left)
}
fn parse_with_recovery_budget(data: &[u8], off: usize, recovery_left: &mut usize) -> Result<StringPool, Error> {
let r = Reader::new(data);
let (t, hdr, size) = chunk(&r, off).ok_or_else(|| Error::Truncated("string pool header".into()))?;
if t != RES_STRING_POOL {
return Err(Error::Malformed(format!("expected a string pool, found chunk type {t:#x}")));
}
if hdr < 28 {
return Err(Error::Malformed("string pool header is smaller than 28 bytes".into()));
}
let r = Reader::new(r.slice(off, size).ok_or_else(|| Error::Truncated("string pool".into()))?);
let count = r.u32_le(8).ok_or_else(|| Error::Truncated("string pool".into()))? as usize;
let styles = r.u32_le(12).ok_or_else(|| Error::Truncated("string pool".into()))? as usize;
let flags = r.u32_le(16).ok_or_else(|| Error::Truncated("string pool".into()))?;
let strings_start = r.u32_le(20).ok_or_else(|| Error::Truncated("string pool".into()))? as usize;
let styles_start = r.u32_le(24).ok_or_else(|| Error::Truncated("string pool".into()))? as usize;
let utf8 = flags & (1 << 8) != 0;
let offsets_end = count
.checked_add(styles)
.and_then(|n| n.checked_mul(4))
.and_then(|n| hdr.checked_add(n))
.ok_or_else(|| Error::Malformed("string pool offset tables are too large".into()))?;
if offsets_end > size || strings_start > size || (count != 0 && strings_start < offsets_end) {
return Err(Error::Malformed("string pool offset tables or string data lie outside their area".into()));
}
if (styles != 0 && styles_start == 0)
|| (styles_start != 0 && (styles_start < offsets_end || styles_start < strings_start || styles_start > size))
{
return Err(Error::Malformed("string pool style data lie outside their area".into()));
}
let end = if styles_start == 0 { size } else { styles_start };
let string_bytes = r.slice(strings_start, end - strings_start).ok_or_else(|| Error::Truncated("string data".into()))?;
let strings_reader = Reader::new(string_bytes);
let mut strings = Vec::with_capacity(count.min(MAX_STRINGS).min(65_536));
let mut bytes_left = BASE_POOL_BYTES.max(size.saturating_mul(3));
let mut recovery_omitted = 0;
for i in 0..count.min(MAX_STRINGS) {
let at = r.u32_le(hdr + i * 4).ok_or_else(|| Error::Truncated("string offsets".into()))? as usize;
let s = if at >= string_bytes.len() {
None
} else if utf8 {
utf8_string(&strings_reader, at, string_bytes.len(), recovery_left, &mut recovery_omitted)
} else {
utf16_string(&strings_reader, at, string_bytes.len())
};
let s = s.unwrap_or_default();
if s.len() > bytes_left {
break;
}
bytes_left -= s.len();
strings.push(s);
}
Ok(StringPool { strings, utf8, declared: count, recovery_omitted })
}
}
fn utf8_len(r: &Reader<'_>, at: usize) -> Option<(usize, usize)> {
let b0 = usize::from(r.u8(at)?);
if b0 & 0x80 != 0 {
let b1 = usize::from(r.u8(at + 1)?);
Some((((b0 & 0x7f) << 8) | b1, 2))
} else {
Some((b0, 1))
}
}
fn utf8_string(r: &Reader<'_>, at: usize, end: usize, recovery_left: &mut usize, recovery_omitted: &mut usize) -> Option<String> {
let (_chars, n1) = utf8_len(r, at)?;
let (mut bytes, n2) = utf8_len(r, at.checked_add(n1)?)?;
let start = at.checked_add(n1 + n2)?;
// Older AAPT keeps only the low 15 length bits; probe matching lengths inside this pool.
loop {
let terminator = start.checked_add(bytes)?;
if terminator >= end {
return None;
}
// The declared candidate costs one read per entry, already bounded by MAX_STRINGS.
if bytes >= 0x8000 {
if *recovery_left == 0 {
*recovery_omitted += 1;
return None;
}
*recovery_left -= 1;
}
if r.u8(terminator)? == 0 {
break;
}
bytes = bytes.checked_add(0x8000)?;
}
let b = r.slice(start, bytes.min(MAX_STRING * 4))?;
Some(String::from_utf8_lossy(b).into_owned())
}
fn utf16_string(r: &Reader<'_>, at: usize, end: usize) -> Option<String> {
let u0 = usize::from(r.u16_le(at)?);
let (len, hdr) = if u0 & 0x8000 != 0 { (((u0 & 0x7fff) << 16) | usize::from(r.u16_le(at + 2)?), 4) } else { (u0, 2) };
let start = at.checked_add(hdr)?;
let terminator = start.checked_add(len.checked_mul(2)?)?;
if terminator.checked_add(2)? > end || r.u16_le(terminator)? != 0 {
return None;
}
let n = len.min(MAX_STRING);
let mut units = Vec::with_capacity(n);
for i in 0..n {
units.push(r.u16_le(start + i * 2)?);
}
Some(String::from_utf16_lossy(&units))
}
/// Record that a string pool was capped or omitted recovery entries.
pub(crate) fn report_partial_string_pool(pool: &StringPool, prefix: &str, truncated: &mut bool, warnings: &mut Vec<String>) {
if pool.strings.len() < pool.declared {
*truncated = true;
warnings.push(format!("{prefix} was capped at {} of {} strings", pool.strings.len(), pool.declared));
}
if pool.recovery_omitted > 0 {
*truncated = true;
warnings.push(format!("{prefix} omitted {} strings after the UTF-8 recovery budget was exhausted", pool.recovery_omitted));
}
}
/// Charge `value` against a retained-byte budget. When it does not fit, report truncation once
/// and return `None`, so a later shorter value can still be kept.
pub(crate) fn retain_value(
left: &mut usize,
value: String,
truncated: &mut bool,
warned: &mut bool,
warnings: &mut Vec<String>,
warning: &str,
) -> Option<String> {
if value.len() > *left {
if !*warned {
warnings.push(warning.to_string());
*warned = true;
}
*truncated = true;
None
} else {
*left -= value.len();
Some(value)
}
}
pub(crate) struct ValueBudget {
left: usize,
warned: bool,
}
impl ValueBudget {
pub(crate) fn new(max_bytes: usize) -> Self {
Self { left: max_bytes, warned: false }
}
pub(crate) fn take(&mut self, value: String, truncated: &mut bool, warnings: &mut Vec<String>, warning: &str) -> Option<String> {
retain_value(&mut self.left, value, truncated, &mut self.warned, warnings, warning)
}
}
/// A typed value (`Res_value`): data type and 32-bit data.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ResValue {
pub data_type: u8,
pub data: u32,
}
impl ResValue {
pub fn type_name(&self) -> &'static str {
match self.data_type {
0x00 => "null",
0x01 => "reference",
0x02 => "attribute",
0x03 => "string",
0x04 => "float",
0x05 => "dimension",
0x06 => "fraction",
0x07 => "dynamic-reference",
0x08 => "dynamic-attribute",
0x10 => "int-dec",
0x11 => "int-hex",
0x12 => "boolean",
0x1c => "color-argb8",
0x1d => "color-rgb8",
0x1e => "color-argb4",
0x1f => "color-rgb4",
_ => "unknown",
}
}
/// Human form; strings come from `pool`.
pub fn format(&self, pool: &StringPool) -> String {
let d = self.data;
match self.data_type {
0x00 => {
if d == 1 {
"@empty".into()
} else {
"@null".into()
}
}
0x01 | 0x07 => {
if d == 0 {
"@null".into()
} else {
format!("@{d:#010x}")
}
}
0x02 | 0x08 => format!("?{d:#010x}"),
0x03 => pool.get(d).unwrap_or("").to_string(),
0x04 => format!("{}", f32::from_bits(d)),
0x05 => complex(d, &["px", "dp", "sp", "pt", "in", "mm"]),
0x06 => complex(d, &["%", "%p"]),
0x10 => (d as i32).to_string(),
0x11 => format!("{d:#x}"),
0x12 => (if d != 0 { "true" } else { "false" }).into(),
0x1c..=0x1f => format!("#{d:08x}"),
_ => format!("{d:#x} (type {:#x})", self.data_type),
}
}
}
fn complex(d: u32, units: &[&str]) -> String {
const RADIX: [f64; 4] = [1.0, 1.0 / 128.0, 1.0 / 32768.0, 1.0 / 8_388_608.0];
let mantissa = f64::from((d & 0xffff_ff00) as i32 >> 8);
let radix = RADIX.get(((d >> 4) & 3) as usize).copied().unwrap_or(1.0);
let mut v = mantissa * radix;
let unit = units.get((d & 0xf) as usize).copied().unwrap_or("?");
if units.len() == 2 {
v *= 100.0;
}
let v = (v * 10_000.0).round() / 10_000.0;
format!("{v}{unit}")
}
/// One attribute of an element.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Attribute {
#[serde(skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
pub name: String,
/// The framework/app resource id of the attribute name, when the resource map gives one.
#[serde(skip_serializing_if = "Option::is_none")]
pub resource_id: Option<String>,
/// Formatted value.
pub value: String,
pub value_type: &'static str,
#[serde(skip)]
pub raw: ResValue,
}
/// One XML node event.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Node {
Start { depth: usize, name: String, namespace: Option<String>, line: u32, attributes: Vec<Attribute> },
End { depth: usize, name: String },
Text { depth: usize, text: String },
Namespace { prefix: String, uri: String },
}
/// A decoded binary XML document.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Document {
pub nodes: Vec<Node>,
#[serde(skip)]
pub pool: StringPool,
pub resource_ids: usize,
pub namespaces: Vec<(String, String)>,
pub truncated: bool,
pub warnings: Vec<String>,
}
/// Names of common framework attributes by resource id, used when a name string was stripped.
pub fn framework_attr(id: u32) -> Option<&'static str> {
Some(match id {
0x0101_0000 => "theme",
0x0101_0001 => "label",
0x0101_0002 => "icon",
0x0101_0003 => "name",
0x0101_0006 => "permission",
0x0101_0007 => "readPermission",
0x0101_0008 => "writePermission",
0x0101_0009 => "protectionLevel",
0x0101_000e => "enabled",
0x0101_000f => "debuggable",
0x0101_0010 => "exported",
0x0101_0018 => "authorities",
0x0101_020c => "minSdkVersion",
0x0101_021b => "versionCode",
0x0101_021c => "versionName",
0x0101_0270 => "targetSdkVersion",
0x0101_0271 => "maxSdkVersion",
0x0101_0280 => "allowBackup",
_ => return None,
})
}
/// Decode a binary XML file.
pub fn parse(data: &[u8]) -> Result<Document, Error> {
parse_with_limits(data, MAX_NODES, MAX_DEPTH, MAX_RETAINED_VALUE_BYTES)
}
fn parse_with_limits(data: &[u8], max_nodes: usize, max_depth: usize, max_value_bytes: usize) -> Result<Document, Error> {
let r = Reader::new(data);
let (t, h, size) = chunk(&r, 0).ok_or_else(|| Error::Truncated("binary XML header".into()))?;
if t != RES_XML {
return Err(Error::Malformed(format!("not binary XML (chunk type {t:#x})")));
}
let data = r.slice(0, size).ok_or_else(|| Error::Truncated("binary XML document".into()))?;
let r = Reader::new(data);
let mut doc = Document::default();
let mut res_map: Vec<u32> = Vec::new();
let mut pos = h;
let mut depth = 0usize;
let mut ns_stack: Vec<(String, String)> = Vec::new();
let mut value_budget = ValueBudget::new(max_value_bytes);
while pos < size {
let Some((ct, ch, cs)) = chunk(&r, pos) else {
doc.truncated = true;
doc.warnings.push(format!("unreadable chunk at offset {pos}"));
break;
};
let extension = match ct {
XML_START_NS | XML_END_NS | XML_END_ELEMENT => 8,
XML_START_ELEMENT => 20,
XML_CDATA => 12,
_ => 0,
};
if extension != 0 && (ch < 16 || cs - ch < extension) {
doc.truncated = true;
doc.warnings.push(format!("incomplete XML node at offset {pos}"));
break;
}
if matches!(ct, XML_START_NS | XML_START_ELEMENT | XML_END_ELEMENT | XML_CDATA) && doc.nodes.len() >= max_nodes {
doc.truncated = true;
doc.warnings.push("XML node limit reached; the remaining events were skipped".into());
break;
}
match ct {
RES_STRING_POOL => match StringPool::parse(data, pos) {
Ok(p) => {
report_partial_string_pool(&p, "string pool", &mut doc.truncated, &mut doc.warnings);
doc.pool = p;
}
Err(e) => doc.warnings.push(format!("string pool: {e}")),
},
XML_RESOURCE_MAP => {
let n = (cs - ch) / 4;
res_map = (0..n.min(MAX_STRINGS)).filter_map(|i| r.u32_le(pos + ch + i * 4)).collect();
doc.resource_ids = res_map.len();
}
XML_START_NS | XML_END_NS => {
let prefix = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string();
let uri = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string();
if ct == XML_START_NS {
if doc.namespaces.len() < 256 {
doc.namespaces.push((prefix.clone(), uri.clone()));
}
if ns_stack.len() < MAX_DEPTH {
ns_stack.push((prefix.clone(), uri.clone()));
}
doc.nodes.push(Node::Namespace { prefix, uri });
} else {
ns_stack.pop();
}
}
XML_START_ELEMENT => {
if depth >= max_depth {
doc.truncated = true;
doc.warnings.push("XML nesting limit reached; the remaining events were skipped".into());
break;
}
let line = r.u32_le(pos + 8).unwrap_or(0);
let ext = pos + ch;
let ns = r.u32_le(ext).and_then(|i| doc.pool.get(i)).map(str::to_string);
let name = r.u32_le(ext + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string();
let a_start = usize::from(r.u16_le(ext + 8).unwrap_or(20));
let a_size = usize::from(r.u16_le(ext + 10).unwrap_or(20));
let a_count = usize::from(r.u16_le(ext + 12).unwrap_or(0));
if a_count != 0 && (a_start < 20 || a_size < 20) {
doc.truncated = true;
doc.warnings.push(format!("element {name}: invalid attribute table layout"));
break;
}
let mut attributes = Vec::new();
for i in 0..a_count {
let relative = a_start + i * a_size;
if relative.checked_add(a_size).is_none_or(|end| end > cs - ch) {
doc.truncated = true;
doc.warnings.push(format!("element {name}: attribute {i} runs past its chunk"));
break;
}
let a = ext + relative;
let value_size = usize::from(r.u16_le(a + 12).unwrap_or(0));
if value_size < 8 || value_size > a_size - 12 {
doc.truncated = true;
doc.warnings.push(format!("element {name}: invalid typed value size in attribute {i}"));
break;
}
let ans = r.u32_le(a).and_then(|i| doc.pool.get(i)).map(str::to_string);
let name_idx = r.u32_le(a + 4).unwrap_or(u32::MAX);
let raw_str = r.u32_le(a + 8).unwrap_or(u32::MAX);
let vt = r.u8(a + 15).unwrap_or(0);
let vd = r.u32_le(a + 16).unwrap_or(0);
let rid = res_map.get(name_idx as usize).copied();
let mut aname = doc.pool.get(name_idx).unwrap_or("").to_string();
if aname.is_empty() {
aname = rid.and_then(framework_attr).map(str::to_string).unwrap_or_else(|| format!("attr_{name_idx}"));
}
let raw = ResValue { data_type: vt, data: vd };
let value = if vt == 0x03 || (raw_str != u32::MAX && vt == 0) {
doc.pool.get(if vt == 0x03 { vd } else { raw_str }).unwrap_or("").to_string()
} else {
raw.format(&doc.pool)
};
let value = value_budget
.take(value, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted")
.unwrap_or_default();
attributes.push(Attribute {
namespace: ans,
name: aname,
resource_id: rid.map(|x| format!("{x:#010x}")),
value,
value_type: raw.type_name(),
raw,
});
}
doc.nodes.push(Node::Start { depth, name, namespace: ns, line, attributes });
depth += 1;
}
XML_END_ELEMENT => {
depth = depth.saturating_sub(1);
let name = r.u32_le(pos + ch + 4).and_then(|i| doc.pool.get(i)).unwrap_or("?").to_string();
doc.nodes.push(Node::End { depth, name });
}
XML_CDATA => {
let text = r.u32_le(pos + ch).and_then(|i| doc.pool.get(i)).unwrap_or("").to_string();
let text = value_budget
.take(text, &mut doc.truncated, &mut doc.warnings, "XML value budget reached; remaining values were omitted")
.unwrap_or_default();
doc.nodes.push(Node::Text { depth, text });
}
_ => {}
}
pos = match pos.checked_add(cs) {
Some(p) => p,
None => break,
};
}
Ok(doc)
}
fn esc(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
impl Document {
fn prefix_for(&self, uri: &str) -> Option<&str> {
self.namespaces.iter().find(|(_, u)| u == uri).map(|(p, _)| p.as_str())
}
/// An XML text rendition (for reading, not byte-exact source).
pub fn to_xml(&self, max_bytes: usize) -> String {
let mut out = String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
let mut first = true;
for n in &self.nodes {
if out.len() > max_bytes {
out.push_str("<!-- truncated -->\n");
break;
}
match n {
Node::Start { depth, name, attributes, .. } => {
out.push_str(&" ".repeat((*depth).min(64)));
out.push('<');
out.push_str(name);
if first {
for (p, u) in &self.namespaces {
out.push_str(&format!(" xmlns:{p}=\"{}\"", esc(u)));
}
first = false;
}
for a in attributes {
let p = a.namespace.as_deref().and_then(|u| self.prefix_for(u)).map(|p| format!("{p}:")).unwrap_or_default();
out.push_str(&format!(" {p}{}=\"{}\"", a.name, esc(&a.value)));
}
out.push_str(">\n");
}
Node::End { depth, name } => {
out.push_str(&" ".repeat((*depth).min(64)));
out.push_str(&format!("</{name}>\n"));
}
Node::Text { depth, text } => {
out.push_str(&" ".repeat((*depth).min(64)));
out.push_str(&esc(text));
out.push('\n');
}
Node::Namespace { .. } => {}
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fixtures as fx;
fn pool_with_offsets(offsets: &[u32], string_data: &[u8]) -> Vec<u8> {
let start = 28 + offsets.len() * 4;
let mut data = vec![0; start];
data[..2].copy_from_slice(&RES_STRING_POOL.to_le_bytes());
data[2..4].copy_from_slice(&28u16.to_le_bytes());
data[8..12].copy_from_slice(&(offsets.len() as u32).to_le_bytes());
data[16..20].copy_from_slice(&0x100u32.to_le_bytes());
data[20..24].copy_from_slice(&(start as u32).to_le_bytes());
for (i, offset) in offsets.iter().enumerate() {
let at = 28 + i * 4;
data[at..at + 4].copy_from_slice(&offset.to_le_bytes());
}
data.extend_from_slice(string_data);
data.resize(data.len().next_multiple_of(4), b'x');
let size = data.len() as u32;
data[4..8].copy_from_slice(&size.to_le_bytes());
data
}
fn append_legacy_ascii(data: &mut Vec<u8>, len: usize) -> u32 {
let offset = data.len() as u32;
let encoded = [0x80 | ((len >> 8) & 0x7f) as u8, (len & 0xff) as u8];
data.extend_from_slice(&encoded);
data.extend_from_slice(&encoded);
data.resize(data.len() + len, b'x');
data.push(0);
offset
}
fn shared_ascii_pool(utf8: bool, count: usize) -> Vec<u8> {
let len = 16_384usize;
let mut strings = Vec::new();
if utf8 {
append_legacy_ascii(&mut strings, len);
} else {
strings.extend_from_slice(&(len as u16).to_le_bytes());
for _ in 0..len {
strings.extend_from_slice(b"x\0");
}
strings.extend_from_slice(&[0, 0]);
}
let mut data = pool_with_offsets(&vec![0; count], &strings);
if !utf8 {
data[16..20].fill(0);
}
data
}
#[test]
fn shared_offsets_spend_a_pool_byte_budget() {
// Each parse keeps 64 MiB of strings: the gate runs the UTF-8 pool with the appended bytes
// (the budget and the appended bytes together), nightly all four.
let full = craft_testkit::hostile::divisor() == 1;
let (encodings, appends): (&[bool], &[bool]) = if full { (&[true, false], &[false, true]) } else { (&[true], &[true]) };
for &utf8 in encodings {
let mut data = shared_ascii_pool(utf8, 8192);
for &appended in appends {
if appended {
// Unrelated bytes after the chunk cannot buy more retained copies.
data.resize(24 << 20, 0);
}
let pool = StringPool::parse(&data, 0).unwrap();
assert_eq!(pool.declared, 8192);
assert_eq!(pool.strings.len(), 4096);
assert_eq!(pool.strings.iter().map(String::len).sum::<usize>(), 64 << 20);
assert_eq!(pool.get(4095).map(str::len), Some(16_384));
assert_eq!(pool.get(4096), None);
}
let data = shared_ascii_pool(utf8, 2);
let pool = StringPool::parse(&data, 0).unwrap();
assert_eq!(pool.strings.len(), 2);
assert_eq!(pool.get(0), pool.get(1));
}
}
fn pool_container(kind: u16, header: usize, children: &[u8]) -> Vec<u8> {
let mut data = vec![0; header];
data[0..2].copy_from_slice(&kind.to_le_bytes());
data[2..4].copy_from_slice(&(header as u16).to_le_bytes());
data.extend_from_slice(children);
let len = data.len() as u32;
data[4..8].copy_from_slice(&len.to_le_bytes());
data
}
#[test]
fn xml_and_resource_tables_disclose_partial_string_pools() {
let pool = shared_ascii_pool(true, 8192);
{
let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap();
assert!(doc.truncated);
assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("4096 of 8192")));
assert_eq!(doc.pool.strings.len(), 4096);
}
let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap();
assert!(table.truncated);
assert_eq!(table.global_strings, 8192);
assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("4096 of 8192")));
for (field, label) in [(268, "type"), (276, "key")] {
let mut package = pool_container(0x0200, 288, &pool);
package[8..12].copy_from_slice(&0x7fu32.to_le_bytes());
package[field..field + 4].copy_from_slice(&288u32.to_le_bytes());
let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap();
assert!(table.truncated, "{label}");
assert!(table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("4096 of 8192")));
assert_eq!(table.packages.len(), 1);
}
}
#[test]
fn repeated_offsets_share_the_utf8_recovery_budget() {
let mut strings = Vec::new();
let long = append_legacy_ascii(&mut strings, 0x8000);
let short = strings.len() as u32;
strings.extend_from_slice(b"\x02\x02ok\0");
let data = pool_with_offsets(&[long, long, long, short], &strings);
let mut left = 2;
let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap();
assert_eq!(left, 0);
assert_eq!(parsed.declared, 4);
assert_eq!(parsed.strings.len(), 4);
assert_eq!(parsed.get(0).map(str::len), Some(0x8000));
assert_eq!(parsed.get(1), parsed.get(0));
assert_eq!(parsed.get(2), Some(""));
assert_eq!(parsed.get(3), Some("ok"));
assert_eq!(parsed.recovery_omitted, 1);
}
#[test]
fn distinct_offsets_share_the_utf8_recovery_budget() {
let mut strings = Vec::new();
let mut offsets: Vec<u32> = (0..3).map(|_| append_legacy_ascii(&mut strings, 0x8000)).collect();
offsets.push(strings.len() as u32);
strings.extend_from_slice(b"\x02\x02ok\0");
let data = pool_with_offsets(&offsets, &strings);
let mut left = 2;
let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap();
assert_eq!(left, 0);
assert_eq!(parsed.get(0).map(str::len), Some(0x8000));
assert_eq!(parsed.get(1).map(str::len), Some(0x8000));
assert_eq!(parsed.get(2), Some(""));
assert_eq!(parsed.get(3), Some("ok"));
assert_eq!(parsed.recovery_omitted, 1);
}
#[test]
fn utf8_recovery_stops_before_a_probe_without_credit() {
let mut strings = Vec::new();
let long = append_legacy_ascii(&mut strings, 0x10000);
let short = strings.len() as u32;
strings.extend_from_slice(b"\x02\x02ok\0");
let data = pool_with_offsets(&[long, short], &strings);
for (allowance, length, remaining) in [(0, 0, 0), (1, 0, 0), (2, 0x10000, 0), (3, 0x10000, 1)] {
let mut left = allowance;
let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap();
assert_eq!(left, remaining);
assert_eq!(parsed.get(0).map(str::len), Some(length));
assert_eq!(parsed.get(1), Some("ok"));
assert_eq!(parsed.recovery_omitted, usize::from(length == 0));
}
}
#[test]
fn short_strings_and_out_of_bounds_candidates_spend_no_recovery_probes() {
let data = pool_with_offsets(&[0, 5], b"\x80\0\x80\0x\x02\x02ok\0");
let mut left = 7;
let parsed = StringPool::parse_with_recovery_budget(&data, 0, &mut left).unwrap();
assert_eq!(left, 7);
assert_eq!(parsed.get(0), Some(""));
assert_eq!(parsed.get(1), Some("ok"));
assert_eq!(parsed.recovery_omitted, 0);
}
fn utf8_recovery_exhausted_pool() -> (Vec<u8>, usize) {
let mut strings = vec![b'x'; 2 * 0x8000 + 16];
strings[..4].copy_from_slice(&[0x80, 0, 0x80, 0]);
let long = append_legacy_ascii(&mut strings, 0x8000);
let short = strings.len() as u32;
strings.extend_from_slice(b"\x02\x02ok\0");
// Offset zero has three in-bounds extra candidates, all nonzero.
let repeated = MAX_RECOVERY_PROBES / 3 + 1;
let mut offsets = vec![0; repeated];
offsets.extend([long, short]);
(pool_with_offsets(&offsets, &strings), repeated)
}
#[test]
fn default_pool_budget_stops_repeated_recovery_before_later_long_strings() {
let (data, repeated) = utf8_recovery_exhausted_pool();
let parsed = StringPool::parse(&data, 0).unwrap();
assert_eq!(parsed.declared, repeated + 2);
assert_eq!(parsed.strings.len(), repeated + 2);
assert!(parsed.strings[..repeated].iter().all(String::is_empty));
assert_eq!(parsed.get(repeated as u32), Some(""));
assert_eq!(parsed.get((repeated + 1) as u32), Some("ok"));
assert!(parsed.recovery_omitted > 0);
}
#[test]
fn xml_and_resource_tables_disclose_recovery_omissions() {
let (pool, repeated) = utf8_recovery_exhausted_pool();
let short_index = (repeated + 1) as u32;
{
let doc = parse(&pool_container(RES_XML, 8, &pool)).unwrap();
assert!(doc.truncated);
assert!(doc.warnings.iter().any(|w| w.contains("string pool") && w.contains("UTF-8 recovery budget")));
assert_eq!(doc.pool.get(short_index), Some("ok"));
assert!(doc.pool.recovery_omitted > 0);
}
let table = crate::arsc::parse(&pool_container(2, 12, &pool), crate::arsc::Limits::default()).unwrap();
assert!(table.truncated);
assert!(table.warnings.iter().any(|w| w.contains("global string pool") && w.contains("UTF-8 recovery budget")));
for (field, label) in [(268, "type"), (276, "key")] {
let mut package = pool_container(0x0200, 288, &pool);
package[8..12].copy_from_slice(&0x7fu32.to_le_bytes());
package[field..field + 4].copy_from_slice(&288u32.to_le_bytes());
let table = crate::arsc::parse(&pool_container(2, 12, &package), crate::arsc::Limits::default()).unwrap();
assert!(table.truncated, "{label}");
assert!(
table.warnings.iter().any(|w| w.contains(&format!("{label} string pool")) && w.contains("UTF-8 recovery budget")),
"{label}: {:?}",
table.warnings
);
}
}
#[test]
fn xml_value_budget_omits_long_copies_and_keeps_a_later_short_value() {
let long = "x".repeat(16);
let attrs = vec![
fx::AxAttr { name: "a", res_id: None, val: fx::AxVal::Str(&long) },
fx::AxAttr { name: "b", res_id: None, val: fx::AxVal::Str(&long) },
fx::AxAttr { name: "c", res_id: None, val: fx::AxVal::Str("ok") },
];
let bytes = fx::axml(&[fx::AxNode::Start("root", attrs), fx::AxNode::End("root")]);
let complete = parse(&bytes).unwrap();
assert!(!complete.truncated);
let Node::Start { attributes, .. } = complete.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else {
panic!("expected the root start");
};
assert_eq!(
attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::<Vec<_>>(),
[("a", long.as_str()), ("b", long.as_str()), ("c", "ok")]
);
let partial = parse_with_limits(&bytes, MAX_NODES, MAX_DEPTH, 20).unwrap();
assert!(partial.truncated);
assert!(partial.warnings.iter().any(|w| w.contains("value budget")));
let Node::Start { attributes, .. } = partial.nodes.iter().find(|n| matches!(n, Node::Start { name, .. } if name == "root")).unwrap() else {
panic!("expected the root start");
};
assert_eq!(
attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect::<Vec<_>>(),
[("a", long.as_str()), ("b", ""), ("c", "ok")]
);
}
fn chunk_at(data: &[u8], kind: u16) -> usize {
let r = Reader::new(data);
let mut pos = 8;
loop {
let (t, _, n) = chunk(&r, pos).unwrap();
if t == kind {
return pos;
}
pos += n;
}
}
#[test]
fn namespace_extensions_follow_the_declared_header() {
let mut data = fx::manifest_axml();
let pos = chunk_at(&data, XML_START_NS);
data.splice(pos + 16..pos + 16, [0xff; 4]);
data[pos + 2..pos + 4].copy_from_slice(&20u16.to_le_bytes());
data[pos + 4..pos + 8].copy_from_slice(&28u32.to_le_bytes());
let len = data.len() as u32;
data[4..8].copy_from_slice(&len.to_le_bytes());
let doc = parse(&data).unwrap();
assert!(doc.warnings.is_empty());
assert_eq!(doc.namespaces[0], ("android".into(), ANDROID_NS.into()));
}
#[test]
fn extended_attribute_strides_keep_each_manifest_value() {
let mut data = fx::manifest_axml();
let pos = chunk_at(&data, XML_START_ELEMENT);
let ext = pos + 16;
// The fixture writes three 20-byte attributes with 8-byte typed values.
for index in (1..=3).rev() {
let end = ext + 20 + index * 20;
data.splice(end..end, [0xff; 4]);
}
data[ext + 10..ext + 12].copy_from_slice(&24u16.to_le_bytes());
data[pos + 4..pos + 8].copy_from_slice(&(36 + 3 * 24u32).to_le_bytes());
let len = data.len() as u32;
data[4..8].copy_from_slice(&len.to_le_bytes());
let doc = parse(&data).unwrap();
assert!(!doc.truncated);
assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
let Node::Start { attributes, .. } = &doc.nodes[1] else {
panic!("expected the manifest start after the namespace");
};
let pairs: Vec<_> = attributes.iter().map(|a| (a.name.as_str(), a.value.as_str())).collect();
assert_eq!(pairs, [("package", fx::PACKAGE), ("versionCode", "42"), ("versionName", "1.2.3")]);
}
#[test]
fn dropping_a_close_event_marks_the_document_partial() {
let bytes = fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::End("root")]);
let complete = parse_with_limits(&bytes, 3, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
assert!(!complete.truncated);
assert!(matches!(complete.nodes.last(), Some(Node::End { depth: 0, .. })));
let partial = parse_with_limits(&bytes, 2, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
assert!(partial.truncated);
assert_eq!(partial.nodes, complete.nodes[..2]);
}
#[test]
fn nesting_limit_keeps_an_exact_prefix_instead_of_saturating_depth() {
let bytes =
fx::axml(&[fx::AxNode::Start("root", vec![]), fx::AxNode::Start("child", vec![]), fx::AxNode::End("child"), fx::AxNode::End("root")]);
let complete = parse_with_limits(&bytes, 5, 2, MAX_RETAINED_VALUE_BYTES).unwrap();
assert!(!complete.truncated);
assert!(matches!(complete.nodes[3], Node::End { depth: 1, .. }));
assert!(matches!(complete.nodes[4], Node::End { depth: 0, .. }));
let partial = parse_with_limits(&bytes, 5, 1, MAX_RETAINED_VALUE_BYTES).unwrap();
assert!(partial.truncated);
assert_eq!(partial.nodes, complete.nodes[..2]);
}
#[test]
fn values_format() {
let p = StringPool { strings: vec!["x".into()], utf8: false, declared: 1, recovery_omitted: 0 };
assert_eq!(ResValue { data_type: 0x05, data: (16 << 8) | 1 }.format(&p), "16dp");
assert_eq!(ResValue { data_type: 0x12, data: 0xffff_ffff }.format(&p), "true");
assert_eq!(ResValue { data_type: 0x1c, data: 0xff00_ff00 }.format(&p), "#ff00ff00");
assert_eq!(ResValue { data_type: 0x10, data: (-5i32) as u32 }.format(&p), "-5");
assert_eq!(ResValue { data_type: 0x03, data: 0 }.format(&p), "x");
assert_eq!(ResValue { data_type: 0x04, data: 1.5f32.to_bits() }.format(&p), "1.5");
}
}
+37
View File
@@ -0,0 +1,37 @@
//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range.
#[derive(Debug, Clone, Copy)]
pub struct Reader<'a> {
data: &'a [u8],
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> {
let end = off.checked_add(len)?;
self.data.get(off..end)
}
pub fn u8(&self, off: usize) -> Option<u8> {
self.data.get(off).copied()
}
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
self.slice(off, N)?.try_into().ok()
}
pub fn u16_le(&self, off: usize) -> Option<u16> {
self.arr(off).map(u16::from_le_bytes)
}
pub fn u32_le(&self, off: usize) -> Option<u32> {
self.arr(off).map(u32::from_le_bytes)
}
}
+376
View File
@@ -0,0 +1,376 @@
//! Test-only XML and resource table fixtures ported from Craft Anything.
pub const PACKAGE: &str = "com.example.notes";
fn u16le(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_le_bytes());
}
fn u32le(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_le_bytes());
}
fn align4(v: &mut Vec<u8>) {
while !v.len().is_multiple_of(4) {
v.push(0);
}
}
/// A string pool chunk (UTF-16, or UTF-8 when `utf8`).
pub fn string_pool(strings: &[&str], utf8: bool) -> Vec<u8> {
let mut data = Vec::new();
let mut offs = Vec::new();
for s in strings {
offs.push(data.len() as u32);
if utf8 {
let n16 = s.encode_utf16().count();
data.push(n16 as u8);
data.push(s.len() as u8);
data.extend_from_slice(s.as_bytes());
data.push(0);
} else {
let units: Vec<u16> = s.encode_utf16().collect();
u16le(&mut data, units.len() as u16);
for u in units {
u16le(&mut data, u);
}
u16le(&mut data, 0);
}
}
align4(&mut data);
let strings_start = 28 + 4 * strings.len();
let mut v = Vec::new();
u16le(&mut v, 0x0001);
u16le(&mut v, 28);
u32le(&mut v, (strings_start + data.len()) as u32);
u32le(&mut v, strings.len() as u32);
u32le(&mut v, 0);
u32le(&mut v, if utf8 { 1 << 8 } else { 0 });
u32le(&mut v, strings_start as u32);
u32le(&mut v, 0);
for o in offs {
u32le(&mut v, o);
}
v.extend_from_slice(&data);
v
}
/// An attribute value in a binary XML element.
#[derive(Debug, Clone, Copy)]
pub enum AxVal<'a> {
Str(&'a str),
Bool(bool),
Int(i32),
Hex(u32),
Ref(u32),
}
#[derive(Debug, Clone)]
pub struct AxAttr<'a> {
pub name: &'a str,
/// Android framework attribute (namespaced, with its resource id).
pub res_id: Option<u32>,
pub val: AxVal<'a>,
}
#[derive(Debug, Clone)]
pub enum AxNode<'a> {
Start(&'a str, Vec<AxAttr<'a>>),
End(&'a str),
}
const NS: &str = "http://schemas.android.com/apk/res/android";
/// Shorthand for an `android:` attribute.
pub fn a<'a>(name: &'a str, res_id: u32, val: AxVal<'a>) -> AxAttr<'a> {
AxAttr { name, res_id: Some(res_id), val }
}
/// Write a binary XML document with the android namespace declared on the root.
pub fn axml(nodes: &[AxNode<'_>]) -> Vec<u8> {
let mut strings: Vec<String> = Vec::new();
let mut ids: Vec<u32> = Vec::new();
for n in nodes {
if let AxNode::Start(_, attrs) = n {
for at in attrs {
if let Some(id) = at.res_id
&& !strings.iter().any(|s| s == at.name)
{
strings.push(at.name.to_string());
ids.push(id);
}
}
}
}
let intern = |s: &str, strings: &mut Vec<String>| -> u32 {
if let Some(i) = strings.iter().position(|x| x == s) {
return i as u32;
}
strings.push(s.to_string());
(strings.len() - 1) as u32
};
let prefix = intern("android", &mut strings);
let uri = intern(NS, &mut strings);
let mut body = Vec::new();
let ns_chunk = |t: u16| {
let mut c = Vec::new();
u16le(&mut c, t);
u16le(&mut c, 16);
u32le(&mut c, 24);
u32le(&mut c, 1);
u32le(&mut c, u32::MAX);
u32le(&mut c, prefix);
u32le(&mut c, uri);
c
};
body.extend(ns_chunk(0x0100));
for (line, n) in nodes.iter().enumerate() {
match n {
AxNode::Start(name, attrs) => {
let nidx = intern(name, &mut strings);
let mut c = Vec::new();
u16le(&mut c, 0x0102);
u16le(&mut c, 16);
u32le(&mut c, (36 + 20 * attrs.len()) as u32);
u32le(&mut c, line as u32 + 2);
u32le(&mut c, u32::MAX);
u32le(&mut c, u32::MAX);
u32le(&mut c, nidx);
u16le(&mut c, 20);
u16le(&mut c, 20);
u16le(&mut c, attrs.len() as u16);
u16le(&mut c, 0);
u16le(&mut c, 0);
u16le(&mut c, 0);
for at in attrs {
let an = intern(at.name, &mut strings);
let (raw, ty, data) = match at.val {
AxVal::Str(s) => {
let i = intern(s, &mut strings);
(i, 0x03u8, i)
}
AxVal::Bool(b) => (u32::MAX, 0x12, if b { u32::MAX } else { 0 }),
AxVal::Int(i) => (u32::MAX, 0x10, i as u32),
AxVal::Hex(h) => (u32::MAX, 0x11, h),
AxVal::Ref(r) => (u32::MAX, 0x01, r),
};
u32le(&mut c, if at.res_id.is_some() { uri } else { u32::MAX });
u32le(&mut c, an);
u32le(&mut c, raw);
u16le(&mut c, 8);
c.push(0);
c.push(ty);
u32le(&mut c, data);
}
body.extend(c);
}
AxNode::End(name) => {
let nidx = intern(name, &mut strings);
let mut c = Vec::new();
u16le(&mut c, 0x0103);
u16le(&mut c, 16);
u32le(&mut c, 24);
u32le(&mut c, line as u32 + 2);
u32le(&mut c, u32::MAX);
u32le(&mut c, u32::MAX);
u32le(&mut c, nidx);
body.extend(c);
}
}
}
body.extend(ns_chunk(0x0101));
let refs: Vec<&str> = strings.iter().map(String::as_str).collect();
let pool = string_pool(&refs, false);
let mut map = Vec::new();
u16le(&mut map, 0x0180);
u16le(&mut map, 8);
u32le(&mut map, (8 + 4 * ids.len()) as u32);
for id in &ids {
u32le(&mut map, *id);
}
let mut out = Vec::new();
u16le(&mut out, 0x0003);
u16le(&mut out, 8);
u32le(&mut out, (8 + pool.len() + map.len() + body.len()) as u32);
out.extend(pool);
out.extend(map);
out.extend(body);
out
}
/// The Notes app's `AndroidManifest.xml`.
pub fn manifest_axml() -> Vec<u8> {
use AxNode::{End, Start};
use AxVal::*;
let name = |v| a("name", 0x0101_0003, Str(v));
axml(&[
Start(
"manifest",
vec![
AxAttr { name: "package", res_id: None, val: Str(PACKAGE) },
a("versionCode", 0x0101_021b, Int(42)),
a("versionName", 0x0101_021c, Str("1.2.3")),
],
),
Start("uses-sdk", vec![a("minSdkVersion", 0x0101_020c, Int(24)), a("targetSdkVersion", 0x0101_0270, Int(34))]),
End("uses-sdk"),
Start("uses-permission", vec![name("android.permission.INTERNET")]),
End("uses-permission"),
Start("uses-permission", vec![name("android.permission.CAMERA")]),
End("uses-permission"),
Start("permission", vec![name("com.example.notes.permission.SYNC"), a("protectionLevel", 0x0101_0009, Hex(2))]),
End("permission"),
Start(
"application",
vec![
name(".NotesApp"),
a("label", 0x0101_0001, Ref(0x7f01_0000)),
a("debuggable", 0x0101_000f, Bool(true)),
a("allowBackup", 0x0101_0280, Bool(false)),
],
),
Start("activity", vec![name(".MainActivity"), a("exported", 0x0101_0010, Bool(true))]),
Start("intent-filter", vec![]),
Start("action", vec![name("android.intent.action.MAIN")]),
End("action"),
Start("category", vec![name("android.intent.category.LAUNCHER")]),
End("category"),
Start("data", vec![a("scheme", 0x0101_0027, Str("notes")), a("host", 0x0101_0028, Str("open"))]),
End("data"),
End("intent-filter"),
End("activity"),
Start("service", vec![name(".SyncService"), a("exported", 0x0101_0010, Bool(false))]),
End("service"),
Start(
"provider",
vec![
name("androidx.core.content.FileProvider"),
a("authorities", 0x0101_0018, Str("com.example.notes.files")),
a("exported", 0x0101_0010, Bool(false)),
],
),
End("provider"),
End("application"),
End("manifest"),
])
}
fn config(lang: &[u8; 2], density: u16, ui_mode: u8, sdk: u16) -> Vec<u8> {
let mut c = vec![0u8; 64];
c[0] = 64;
if lang != b"\0\0" {
c[8..10].copy_from_slice(lang);
}
c[14..16].copy_from_slice(&density.to_le_bytes());
c[24..26].copy_from_slice(&sdk.to_le_bytes());
c[29] = ui_mode;
c
}
fn type_spec(id: u8, entries: u32) -> Vec<u8> {
let mut c = Vec::new();
u16le(&mut c, 0x0202);
u16le(&mut c, 16);
u32le(&mut c, 16 + 4 * entries);
c.push(id);
c.push(0);
u16le(&mut c, 0);
u32le(&mut c, entries);
for _ in 0..entries {
u32le(&mut c, 0);
}
c
}
/// A type chunk from already-encoded entries.
fn type_chunk(id: u8, cfg: &[u8], entries: &[Vec<u8>]) -> Vec<u8> {
let header = 20 + cfg.len();
let start = header + 4 * entries.len();
let mut offs = Vec::new();
let mut body = Vec::new();
for e in entries {
offs.push(body.len() as u32);
body.extend_from_slice(e);
}
let mut c = Vec::new();
u16le(&mut c, 0x0201);
u16le(&mut c, header as u16);
u32le(&mut c, (start + body.len()) as u32);
c.push(id);
c.push(0);
u16le(&mut c, 0);
u32le(&mut c, entries.len() as u32);
u32le(&mut c, start as u32);
c.extend_from_slice(cfg);
for o in offs {
u32le(&mut c, o);
}
c.extend(body);
c
}
fn simple_entry(key: u32, ty: u8, data: u32) -> Vec<u8> {
let mut e = Vec::new();
u16le(&mut e, 8);
u16le(&mut e, 0);
u32le(&mut e, key);
u16le(&mut e, 8);
e.push(0);
e.push(ty);
u32le(&mut e, data);
e
}
/// `resources.arsc`: `string/app_name` and `string/greeting` in the default locale and French,
/// and one `style/AppTheme` bag (night, xhdpi, v21) with a parent and a colour item.
pub fn resources_arsc() -> Vec<u8> {
let global = string_pool(&["Notes", "Hello", "Notes FR", "Bonjour"], true);
let types = string_pool(&["string", "style"], false);
let keys = string_pool(&["app_name", "greeting", "AppTheme"], false);
let mut bag = Vec::new();
u16le(&mut bag, 16);
u16le(&mut bag, 1);
u32le(&mut bag, 2);
u32le(&mut bag, 0x0103_0005);
u32le(&mut bag, 1);
u32le(&mut bag, 0x7f03_0000);
u16le(&mut bag, 8);
bag.push(0);
bag.push(0x1c);
u32le(&mut bag, 0xff33_6699);
let mut chunks = Vec::new();
chunks.extend(type_spec(1, 2));
chunks.extend(type_chunk(1, &config(b"\0\0", 0, 0, 0), &[simple_entry(0, 3, 0), simple_entry(1, 3, 1)]));
chunks.extend(type_chunk(1, &config(b"fr", 0, 0, 0), &[simple_entry(0, 3, 2), simple_entry(1, 3, 3)]));
chunks.extend(type_spec(2, 1));
chunks.extend(type_chunk(2, &config(b"\0\0", 320, 0x20, 21), &[bag]));
let header = 288usize;
let mut pkg = Vec::new();
u16le(&mut pkg, 0x0200);
u16le(&mut pkg, header as u16);
u32le(&mut pkg, (header + types.len() + keys.len() + chunks.len()) as u32);
u32le(&mut pkg, 0x7f);
let mut name = [0u16; 128];
for (i, u) in PACKAGE.encode_utf16().enumerate() {
name[i] = u;
}
for u in name {
u16le(&mut pkg, u);
}
u32le(&mut pkg, header as u32);
u32le(&mut pkg, 2);
u32le(&mut pkg, (header + types.len()) as u32);
u32le(&mut pkg, 3);
u32le(&mut pkg, 0);
pkg.extend(types);
pkg.extend(keys);
pkg.extend(chunks);
let mut out = Vec::new();
u16le(&mut out, 0x0002);
u16le(&mut out, 12);
u32le(&mut out, (12 + global.len() + pkg.len()) as u32);
u32le(&mut out, 1);
out.extend(global);
out.extend(pkg);
out
}
+17
View File
@@ -0,0 +1,17 @@
//! Bounded readers for compiled Android XML and resource tables.
pub mod arsc;
pub mod axml;
mod bytes;
#[cfg(test)]
mod fixtures;
/// Failure to decode the Android wire format.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
/// A required record did not fit within the available bytes.
#[error("truncated: {0}")]
Truncated(String),
/// The available bytes do not form the required structure.
#[error("malformed: {0}")]
Malformed(String),
}
+31
View File
@@ -0,0 +1,31 @@
[package]
name = "craft-appkit"
description = "The macOS menu-tracking observers and Save panel calls that need `unsafe`, behind a safe API, so no other crate allows `unsafe`."
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through
# `NSNotificationCenter` with a block. A Save panel made with `-init`, and the target of a pop-up menu's action.
[target.'cfg(target_os = "macos")'.dependencies]
block2 = "0.6.2"
objc2 = { version = "0.6.4", default-features = false, features = ["std"] }
objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSButton", "NSControl", "NSMenu", "NSPanel", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSView", "NSWindow"] }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSObject", "NSOperation", "NSString"] }
# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's
# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one
# workspace lint.
[lints.rust]
unsafe_code = "deny"
missing_docs = "warn"
unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] }
[lints.clippy]
cognitive_complexity = "deny"
too_many_arguments = "deny"
wildcard_imports = "deny"
dbg_macro = "warn"
todo = "warn"
+39
View File
@@ -0,0 +1,39 @@
//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking, and the
//! Save panel calls in `save_panel`. macOS only; the crate is empty elsewhere.
//!
//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every
//! block says why it is sound.
#![warn(missing_docs)]
#![cfg(target_os = "macos")]
#![allow(unsafe_code)]
use std::ptr::NonNull;
use std::sync::{Arc, Once};
use block2::RcBlock;
use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification};
use objc2_foundation::{NSNotification, NSNotificationCenter};
pub mod save_panel;
/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)`
/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once
/// for the process; a later call replaces nothing and does nothing.
pub fn observe_menu_tracking(on_change: Arc<dyn Fn(bool) + Send + Sync>) {
static OBSERVE: Once = Once::new();
OBSERVE.call_once(|| {
// SAFETY: AppKit initializes these immutable notification-name constants before any code of the app runs.
let names = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] };
let center = NSNotificationCenter::defaultCenter();
for (name, tracking) in names {
let on_change = on_change.clone();
let block = RcBlock::new(move |_: NonNull<NSNotification>| on_change(tracking));
// SAFETY: `name` is one of AppKit's notification names and the block takes the notification by pointer
// without reading it. The center copies the block and keeps the observer for the process's lifetime;
// nothing removes it, so the returned token is not needed.
unsafe {
center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block);
}
}
});
}
+64
View File
@@ -0,0 +1,64 @@
//! The Save panel calls that need `unsafe`: making a panel that may be nil, and a pop-up menu's action.
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2::{ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send, sel};
use objc2_app_kit::{NSPopUpButton, NSSavePanel};
use objc2_foundation::{NSObject, NSObjectProtocol};
/// A new Save panel, or `None` when AppKit returns nil. `+[NSSavePanel savePanel]` returns nil on some systems
/// (storytold/vectorcraft#5980), and objc2's `NSSavePanel::savePanel` panics on it.
pub fn new_save_panel(mtm: MainThreadMarker) -> Option<Retained<NSSavePanel>> {
// SAFETY: `-init` is the initializer of a bare panel, called once on the allocation. The result is typed as
// `Option`, so nil is `None`.
let panel: Option<Retained<NSSavePanel>> = unsafe { msg_send![NSSavePanel::alloc(mtm), init] };
if panel.is_some() {
return panel;
}
// SAFETY: a class method that returns an autoreleased panel or nil, typed as `Option`.
unsafe { msg_send![NSSavePanel::class(), savePanel] }
}
/// The closure a [`PopUpChoice`] calls.
pub struct Ivars {
on_choose: Box<dyn Fn(usize)>,
}
define_class!(
// SAFETY: NSObject has no subclassing requirements, and the class implements no `Drop`.
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[ivars = Ivars]
#[name = "CraftPopUpChoice"]
/// The target of a pop-up menu's action; see [`on_choose`].
pub struct PopUpChoice;
// SAFETY: NSObjectProtocol has no additional requirements.
unsafe impl NSObjectProtocol for PopUpChoice {}
impl PopUpChoice {
// SAFETY: NSControl's target-action sends the pop-up button as the one object argument.
#[unsafe(method(choose:))]
fn choose(&self, sender: &NSPopUpButton) {
if let Ok(index) = usize::try_from(sender.indexOfSelectedItem()) {
(self.ivars().on_choose)(index);
}
}
}
);
/// Calls `on_choose` with the index of the item the user chooses in `popup`. A control does not retain its target,
/// so the caller keeps the returned object for as long as `popup` can send its action.
pub fn on_choose(mtm: MainThreadMarker, popup: &NSPopUpButton, on_choose: impl Fn(usize) + 'static) -> Retained<PopUpChoice> {
let this = PopUpChoice::alloc(mtm).set_ivars(Ivars { on_choose: Box::new(on_choose) });
// SAFETY: NSObject's designated initializer, called once on the allocated subclass.
let target: Retained<PopUpChoice> = unsafe { msg_send![super(this), init] };
let object: &AnyObject = &target;
// SAFETY: `choose:` takes the sender, the signature a control's action is sent with, and the caller keeps
// `target` alive while `popup` can send it (the documentation above).
unsafe {
popup.setTarget(Some(object));
popup.setAction(Some(sel!(choose:)));
}
target
}
+5 -1
View File
@@ -1,4 +1,5 @@
[package]
autotests = false
name = "craft-atomic"
version.workspace = true
edition.workspace = true
@@ -10,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit
[lints]
workspace = true
# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with
# explicit size queries (`fgetxattr_query`).
[target.'cfg(target_vendor = "apple")'.dependencies]
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] }
+22 -1
View File
@@ -6,7 +6,7 @@ Extracted from the storage engine in **PhotoCraft** (refs #2, #14), it guarantee
## Core Guarantees: Atomicity vs. Durability
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; sweeping orphaned staging files is delegated to consuming application recovery routines. The destination file itself is never corrupted.
1. **Atomicity (All-or-Nothing Replacement)**: `atomic_write` never truncates or overwrites the destination in place. It stages content in a hidden temporary file beside the destination (`.{stem}.{pid}-{n}.craft_tmp`), guaranteeing same-volume rename semantics (`EXDEV`-free). An external reader never sees a partial write. If an error occurs during staging or rename, the destination retains its prior bytes and the staging file is unlinked in user space. An abnormal process exit (e.g. `SIGKILL`, crash, or power loss) bypasses user-space cleanup and leaves the staging file on disk; the application removes orphaned staging files by calling `sweep_temp_files` for the folder (see "Removing Orphaned Staging Files" below). The destination file itself is never corrupted.
2. **Durability & Ordering Boundaries**:
- **Content Flush**: Before rename, staging file bytes are flushed to physical storage media (`sync_file`, issuing `F_FULLFSYNC` on macOS/APFS with SMB `fsync` fallback).
- **Directory Flush (Unix)**: After rename, syncing the parent directory table (`sync_dir`) is attempted on a best-effort basis. If directory sync fails, the error is ignored because the rename has already committed and the destination has already been replaced.
@@ -63,6 +63,27 @@ let path = Path::new("export.png");
write_new(path, b"png bytes...").expect("exclusive write");
```
### Removing Orphaned Staging Files
```rust
use std::path::Path;
use std::time::Duration;
use craft_atomic::sweep_temp_files;
// Removes staging files in scenes/ that were last modified an hour or more ago.
// Returns how many were removed.
let removed = sweep_temp_files(Path::new("scenes"), Duration::from_secs(3600)).unwrap_or(0);
```
`sweep_temp_files` removes only regular files whose names have the staging form, never follows
a symbolic link, and does not search subfolders. A save updates its staging file's modification
time only while it writes bytes, not while it flushes or renames, and removing the staging file
makes that save fail. Choose a minimum age longer than the longest time any save into the folder,
by any process including the calling one, may go without writing, counting the final flush and
rename. On Windows, a write may not update the modification time until the staging file's handle
closes, so choose a minimum age longer than the longest whole save, from the staging file's
creation through the rename. Entries that cannot be removed are left in place.
### Document Permissions and Private Data
The free functions and `WriteOptions::default()` use `NewFilePermissions::PlatformDefault`.
+293 -746
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 6830 files, more files were not shown because too many files have changed in this diff. Show more