diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ea3ce72..7299842 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,10 @@ jobs: env: ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} run: python3 community/optics/smoke.py "$ANIMATHIO_CLI" target/plugins + - name: Test Net Lab on released 2.3.0 + env: + ANIMATHIO_CLI: ${{ steps.host-2-3-0.outputs.cli }} + run: python3 community/network/smoke.py "$ANIMATHIO_CLI" target/plugins - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: plugins diff --git a/README.md b/README.md index a7f56d8..35f14d7 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ MIT licensed, like AniMathIO. Plugins are sandboxed WebAssembly components. | --- | --- | --- | --- | --- | --- | | [Code Snippets](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | AniMathIO | Syntax-highlighted code with type-on reveal and token morph animations | MIT AND OFL-1.1 | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/code-snippets) | | [Molecule Studio](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | AniMathIO | Self-drawing 2D molecular structures and reactions from SMILES, with CPK colors and wedge/dash stereo | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/molecule) | +| [Net Lab](https://github.com/AniMathIO/plugins/tree/HEAD/community/network) | AniMathIO | Animate ARP, ICMP ping, TCP, DHCP, DNS and traceroute over teaching topologies | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/network) | | [Ray Optics](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | AniMathIO | Animated lens and mirror rays, Snell refraction, total internal reflection and prism dispersion | MIT | 1.1.0 | [AniMathIO/plugins](https://github.com/AniMathIO/plugins/tree/HEAD/community/optics) | diff --git a/community-plugins.json b/community-plugins.json index 7de951e..51a8cf3 100644 --- a/community-plugins.json +++ b/community-plugins.json @@ -31,6 +31,16 @@ "path": "community/optics", "license": "MIT", "min_abi": "1.1.0" + }, + { + "id": "io.github.animathio.network", + "name": "Net Lab", + "author": "AniMathIO", + "description": "Animate ARP, ICMP ping, TCP, DHCP, DNS and traceroute over teaching topologies", + "repo": "AniMathIO/plugins", + "path": "community/network", + "license": "MIT", + "min_abi": "1.1.0" } ], "delisted": [] diff --git a/community/network/Cargo.lock b/community/network/Cargo.lock new file mode 100644 index 0000000..b7db9e2 --- /dev/null +++ b/community/network/Cargo.lock @@ -0,0 +1,834 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "auditable-serde" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7bf8143dfc3c0258df908843e169b5cc5fcf76c7718bd66135ef4a9cd558c5" +dependencies = [ + "semver", + "serde", + "serde_json", + "topological-sort", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "network" +version = "1.0.0" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" +dependencies = [ + "serde", + "serde_core", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "spdx" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e17e880bafaeb362a7b751ec46bdc5b61445a188f80e0606e68167cd540fa3" +dependencies = [ + "smallvec", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "topological-sort" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "wasm-encoder" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bb72f02e7fbf07183443b27b0f3d4144abf8c114189f2e088ed95b696a7822" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1ef0faabbbba6674e97a56bee857ccddf942785a336c8b47b42373c922a91d" +dependencies = [ + "anyhow", + "auditable-serde", + "flate2", + "indexmap", + "serde", + "serde_derive", + "serde_json", + "spdx", + "url", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e7091ed6c9abfa4e0a2ef3b39d0539da992d841fcf32c255f64fb98764ffee5" +dependencies = [ + "wit-bindgen-rt", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "398c650cec1278cfb72e214ba26ef3440ab726e66401bd39c04f465ee3979e6b" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rt" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68faed92ae696b93ea9a7b67ba6c37bf09d72c6d9a70fa824a743c3020212f11" +dependencies = [ + "bitflags", + "futures", + "once_cell", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83903c8dcd8084a8a67ae08190122cf0e25dc37bdc239070a00f47e22d3f0aae" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn 2.0.119", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7bf7f20495bcc7dc9f24c5fbcac9e919ca5ebdb7a1b1841d74447d3c8dd0c60" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.227.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/community/network/Cargo.toml b/community/network/Cargo.toml new file mode 100644 index 0000000..1bd5905 --- /dev/null +++ b/community/network/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "network" +version = "1.0.0" +edition = "2021" +license = "MIT" +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +wit-bindgen = "=0.40.0" + +[profile.release] +opt-level = 3 +lto = true +strip = "debuginfo" + +[workspace] diff --git a/community/network/NOTICE b/community/network/NOTICE new file mode 100644 index 0000000..3081661 --- /dev/null +++ b/community/network/NOTICE @@ -0,0 +1,25 @@ +Net Lab for AniMathIO +Copyright (c) 2026 AniMathIO contributors. MIT (see ../../LICENSE). + +Protocol sequencing references + +michael-borck/netsim, c3075e7fe65b7e17515d802eaef625bab751af58 +https://github.com/michael-borck/netsim/tree/c3075e7fe65b7e17515d802eaef625bab751af58 +MIT, copyright (c) 2026 Michael Borck. See assets/netsim-michael-borck-LICENSE. +The ARP, ping, DHCP and traceroute flows illustrate ordering at each hop, +switch flooding, reply paths and the moment a table entry is learned. Net Lab +implements those teaching sequences as bounded, authored Rust timelines. + +joxorsayan/netsim, fb07a807f86f2daa64822b54239e3fcb53850693 +https://github.com/joxorsayan/netsim/tree/fb07a807f86f2daa64822b54239e3fcb53850693 +MIT, copyright (c) 2025 Sayan Roy Chowdhury. See assets/netsim-joxorsayan-LICENSE. +The switching, ARP, ICMP and DHCP examples informed the scope and order of the +teaching sequences. + +Protocol behavior also follows RFC 826 (ARP), 792 (ICMPv4), 1812 (IPv4 +forwarding), 2131 (DHCP), 1034/1035 (DNS) and 9293 (TCP). The implementation, +device glyphs and artwork were authored for this plugin. The sample exchanges +use private LAN addresses and the RFC 2606 and RFC 5737 example namespaces. + +wit-bindgen and its dependencies retain their respective licenses. Cargo.lock +records the resolved versions. diff --git a/community/network/README.md b/community/network/README.md new file mode 100644 index 0000000..e9ba04e --- /dev/null +++ b/community/network/README.md @@ -0,0 +1,103 @@ +# Net Lab + +Net Lab animates six networking lessons as an AniMathIO clip source. Scrub +packet flight, follow the active hop, and watch a switch learn source MAC +addresses or a host fill its ARP cache. + +Plugin ID `io.github.animathio.network` · ABI 1.1.0 · MIT + +## Build and use + +```sh +rustup target add wasm32-wasip2 +bash community/network/build.sh +ANIMATHIO_PLUGIN_DIR="$PWD/community/network/target" animathio +``` + +Run these commands from the plugins repository root. The build produces +`community/network/target/network.amplugin`. When using the plugin directory +override with other plugin clips, include their bundles in that directory too. + +Add **Net Lab** from the Library and choose a scenario and topology in the +inspector. Keyframe `progress` from 0 to 1 over the part of the clip where you +want the exchange to play. Use two equal keyframe values to pause on a frame. +Progress at 1 holds on the completed timeline and learned table state. + +## Scenarios + +| Preset | What plays | +| --- | --- | +| `ping` | Resolve the server or gateway with ARP, send an ICMP Echo Request, and follow the reply. On the routed preset the router resolves the server on its own LAN. | +| `arp` | Flood the request on the LAN, follow the unicast reply, then ping the same peer using the cached MAC. | +| `tcp` | SYN, SYN-ACK and ACK, followed by an HTTP GET, 200 OK and an orderly close. | +| `dhcp` | Broadcast Discover and Request, receive unicast Offer and ACK, and see the client acquire its address. The routed preset uses the gateway's DHCP service on the client LAN. | +| `dns` | Ask the recursive resolver for `example.test`. The resolver knows the authority's address, queries it on a cache miss, and returns the A record. | +| `traceroute` | Follow UDP probes with increasing TTL. A router returns ICMP Time Exceeded and the destination returns ICMP Port Unreachable. | + +Each event animates one link hop. A switch flood can send copies along multiple +links simultaneously. ARP and MAC entries appear once the learning hop finishes. +The route panel shows the router's configured connected networks. TCP and +traceroute start with endpoint ARP already resolved, and DNS elides ARP beyond +the initial client-side lookup. The transport lessons show TCP flags and the +order of TCP and UDP messages. Transport port numbers and TCP sequence and +acknowledgment numbers are omitted. The lessons use IPv4 and a single switch with +optional routing. Timing is illustrative, with equal time per hop and brief +holds before and after the exchange. + +## Parameters + +| Parameter | Default | Meaning | +| --- | --- | --- | +| `scenario` | `ping` | Choose one of the six lessons above. | +| `topology` | `through-router` | `single-switch` for one LAN, `through-router` for separate LANs. DNS adds an authoritative service to the selected preset. | +| `progress` | 1 | Timeline position from 0 to 1. | +| `steps` | 24 | Maximum link hops to play, from 1 to 200. Values past the lesson's last hop play the full lesson. | +| `labels` | `full` | `full` adds port names and explanatory notes. A port name is hidden briefly if a packet leaves too little room beside its link. `brief` abbreviates packet labels. `none` uses dots for packets and hides port and IP labels. | +| `show_tables` | true | Show the state panel. | +| `table` | `auto` | Select `mac`, `arp`, or `route` manually. Auto uses ARP for ping and DNS, routing for traceroute on the routed preset, and MAC for the other lessons. | +| `packet_size` | 2.4 | Packet size, 0.5–6% of the shorter canvas edge. | +| `accent` | `#4FC3F7` | Color for device details and active step emphasis. Packet color distinguishes protocols. | +| `show_step_list` | true | Show the packet timeline and highlight the current hop. | +| `speed_lines` | true | Draw short trails behind moving packets. | + +## Screenshots + +Rendered with the released AniMathIO 2.3.0 CLI. + +| ICMP ping | ARP flood | Learned ARP cache | +| --- | --- | --- | +| ![Routed ICMP Echo Request with the gateway MAC cached](screenshots/ping.png) | ![Switch floods the ARP request to PC2 and the server](screenshots/arp-flood.png) | ![PC1 uses its learned ARP entry to ping PC2](screenshots/arp-cache.png) | + +| TCP handshake | DHCP request | DNS answer | Traceroute | +| --- | --- | --- | --- | +| ![SYN-ACK returns to PC1](screenshots/tcp.png) | ![DHCP Request fans out while PC1 waits for its lease](screenshots/dhcp.png) | ![The authority returns a DNS answer to the resolver](screenshots/dns.png) | ![Router forwards a UDP probe with TTL 1](screenshots/traceroute.png) | + +## Tests and implementation + +```sh +CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 \ + nice -n 19 ionice -c3 cargo test --manifest-path community/network/Cargo.toml --locked +python3 -m pip install Pillow +python3 community/network/smoke.py /path/to/animathio-cli community/network/target --screenshots +``` + +The smoke script renders both topology presets at five progress values per +scenario, with tables visible and hidden. It verifies exact PNG repeatability, +host-sampled progress keyframes, diagnostics and parameter changes. The native +tests cover hop order, switch flooding, table replay, the DHCP lease boundary, +and probe TTL before and after routing. + +Every frame reconstructs the event list and table prefix from its parameters. +The longest lesson contains 24 hops and the largest topology has five devices. +The plugin draws original vector glyphs and uses the host's text drawing +primitive. Rendering uses no host imports or capabilities and is independent +of wall clock and seek order. + +The MIT netsim projects informed the protocol sequencing. Their credits and +licenses are in [NOTICE](NOTICE). Protocol references include +[RFC 826](https://www.rfc-editor.org/rfc/rfc826.html), +[RFC 792](https://www.rfc-editor.org/rfc/rfc792.html), +[RFC 1812](https://www.rfc-editor.org/rfc/rfc1812.html), +[RFC 9293](https://www.rfc-editor.org/rfc/rfc9293.html), +[RFC 2131](https://www.rfc-editor.org/rfc/rfc2131.html) and +[RFC 1034](https://www.rfc-editor.org/rfc/rfc1034.html). diff --git a/community/network/assets/netsim-joxorsayan-LICENSE b/community/network/assets/netsim-joxorsayan-LICENSE new file mode 100644 index 0000000..c7d6433 --- /dev/null +++ b/community/network/assets/netsim-joxorsayan-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Sayan Roy Chowdhury + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/community/network/assets/netsim-michael-borck-LICENSE b/community/network/assets/netsim-michael-borck-LICENSE new file mode 100644 index 0000000..7a4f089 --- /dev/null +++ b/community/network/assets/netsim-michael-borck-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Michael Borck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/community/network/build.sh b/community/network/build.sh new file mode 100755 index 0000000..50a1d1a --- /dev/null +++ b/community/network/build.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +export CARGO_BUILD_JOBS=2 CARGO_PROFILE_DEV_DEBUG=0 CARGO_INCREMENTAL=0 +export CARGO_TARGET_DIR="$PWD/target" +runner=(cargo) +if [[ "$OSTYPE" == linux* ]]; then runner=(nice -n 19 ionice -c3 cargo); fi +"${runner[@]}" build --target wasm32-wasip2 --release --locked +python3 - <<'PACKAGE' +import pathlib, tomllib, zipfile +root = pathlib.Path('.') +name = tomllib.loads((root / 'Cargo.toml').read_text())['package']['name'] +out = root / 'target' / (name + '.amplugin') +with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as z: + z.write('plugin.toml', 'plugin.toml') + z.write('NOTICE', 'NOTICE') + z.write('../../LICENSE', 'LICENSE') + for notice in ['netsim-michael-borck-LICENSE', 'netsim-joxorsayan-LICENSE']: + z.write('assets/' + notice, 'licenses/' + notice) + z.write(f"target/wasm32-wasip2/release/{name.replace('-', '_')}.wasm", 'plugin.wasm') +print(out) +PACKAGE diff --git a/community/network/plugin.toml b/community/network/plugin.toml new file mode 100644 index 0000000..7359d64 --- /dev/null +++ b/community/network/plugin.toml @@ -0,0 +1,7 @@ +api_version = "1.1.0" +id = "io.github.animathio.network" +name = "Net Lab" +version = "1.0.0" +description = "Animate ARP, ICMP ping, TCP, DHCP, DNS and traceroute over teaching topologies" +kinds = ["clip-source"] +capabilities = [] diff --git a/community/network/screenshots/arp-cache.png b/community/network/screenshots/arp-cache.png new file mode 100644 index 0000000..fc3b255 Binary files /dev/null and b/community/network/screenshots/arp-cache.png differ diff --git a/community/network/screenshots/arp-flood.png b/community/network/screenshots/arp-flood.png new file mode 100644 index 0000000..e31eea9 Binary files /dev/null and b/community/network/screenshots/arp-flood.png differ diff --git a/community/network/screenshots/dhcp.png b/community/network/screenshots/dhcp.png new file mode 100644 index 0000000..da652a2 Binary files /dev/null and b/community/network/screenshots/dhcp.png differ diff --git a/community/network/screenshots/dns.png b/community/network/screenshots/dns.png new file mode 100644 index 0000000..a37c17c Binary files /dev/null and b/community/network/screenshots/dns.png differ diff --git a/community/network/screenshots/ping.png b/community/network/screenshots/ping.png new file mode 100644 index 0000000..8dffc55 Binary files /dev/null and b/community/network/screenshots/ping.png differ diff --git a/community/network/screenshots/tcp.png b/community/network/screenshots/tcp.png new file mode 100644 index 0000000..4676ea8 Binary files /dev/null and b/community/network/screenshots/tcp.png differ diff --git a/community/network/screenshots/traceroute.png b/community/network/screenshots/traceroute.png new file mode 100644 index 0000000..c64a766 Binary files /dev/null and b/community/network/screenshots/traceroute.png differ diff --git a/community/network/smoke.py b/community/network/smoke.py new file mode 100644 index 0000000..85fb8ab --- /dev/null +++ b/community/network/smoke.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Verify Net Lab on a released AniMathIO CLI and regenerate README screenshots.""" +import argparse +import io +import json +import os +from pathlib import Path +import subprocess +import zipfile + +from PIL import Image + +ROOT = Path(__file__).resolve().parent +WORK = ROOT / "target" / "smoke" +PLUGIN_ID = "io.github.animathio.network" +SCENARIOS = ("ping", "arp", "tcp", "dhcp", "dns", "traceroute") +TOPOLOGIES = ("single-switch", "through-router") +BACKGROUND = (12, 18, 27) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("cli", type=Path) + parser.add_argument("plugin_dir", type=Path) + parser.add_argument("--screenshots", action="store_true") + args = parser.parse_args() + for folder in ("config", "cache", "data", "tmp"): + (WORK / folder).mkdir(parents=True, exist_ok=True) + env = dict( + os.environ, + ANIMATHIO_PLUGIN_DIR=str(args.plugin_dir.resolve()), + ANIMATHIO_AUDIO="none", + XDG_CONFIG_HOME=str(WORK / "config"), + XDG_CACHE_HOME=str(WORK / "cache"), + XDG_DATA_HOME=str(WORK / "data"), + TMPDIR=str(WORK / "tmp"), + PIPEWIRE_REMOTE="animathio-silent-no-such-remote", + PULSE_SERVER="unix:/nonexistent/animathio-silent", + ) + cli = args.cli.resolve() + + def run(*options): + command = [cli, *map(str, options)] + result = subprocess.run(command, env=env, text=True, capture_output=True, timeout=30) + if result.returncode or any(word in result.stderr.lower() for word in ( + "failed", "trap", "placeholder", "not loaded", "unresolved", + )): + raise RuntimeError(f"{command}: {result.stdout}{result.stderr}") + return result.stdout + + sample = WORK / "sample.amio" + sample.unlink(missing_ok=True) + run("new-sample", "-o", sample) + with zipfile.ZipFile(sample) as bundle: + project = json.loads(bundle.read("project.json")) + project["assets"] = {} + project["width"] = 1280 + project["height"] = 720 + project["tracks"] = project["tracks"][:1] + clip = project["tracks"][0]["clips"]["1"] + clip["animations"] = [] + clip["effects"] = [] + + def render(name, frame=0, expect_error=False, **params): + clip["kind"] = {"Plugin": {"plugin_id": PLUGIN_ID, "params": params}} + project_file = WORK / (name + ".amio") + with zipfile.ZipFile(project_file, "w", zipfile.ZIP_DEFLATED) as bundle: + bundle.writestr("project.json", json.dumps(project)) + png = WORK / (name + ".png") + png.unlink(missing_ok=True) + run("render", project_file, "--frame", frame, "-o", png) + encoded = png.read_bytes() + image = Image.open(io.BytesIO(encoded)).convert("RGB") + colors = image.getcolors(image.width * image.height) + # AniMathIO 2.3.0 renders plugin diagnostics as a checkerboard frame. + # Check the authored background and saturated artwork to catch fallbacks. + assert (image.getpixel((4, 4)) == BACKGROUND) != expect_error, name + has_accent = any(max(rgb) - min(rgb) > 55 for _, rgb in colors) + assert has_accent != expect_error, name + if not expect_error: + assert len(colors) > 30, name + return encoded + + for topology in TOPOLOGIES: + for scenario in SCENARIOS: + for show_tables in (True, False): + prefix = f"{topology}-{scenario}-tables-{show_tables}" + samples = [ + render(f"{prefix}-{int(progress * 100):03}", topology=topology, + scenario=scenario, progress=progress, show_tables=show_tables) + for progress in (0, 0.25, 0.5, 0.75, 1) + ] + assert len(set(samples)) == len(samples), prefix + print(f"PASS {topology} / {scenario} at five progress values with tables on and off") + + midpoint = render("tcp-midpoint", scenario="tcp", progress=0.5) + assert midpoint == render("tcp-repeat", scenario="tcp", progress=0.5) + assert midpoint != render("tcp-brief", scenario="tcp", progress=0.5, labels="brief") + assert midpoint != render( + "tcp-no-panels", scenario="tcp", progress=0.5, show_tables=False, show_step_list=False, + ) + assert midpoint != render("tcp-no-speed-lines", scenario="tcp", progress=0.5, speed_lines=False) + assert midpoint != render("tcp-large-packet", scenario="tcp", progress=0.5, packet_size=6) + assert midpoint != render("tcp-short-timeline", scenario="tcp", progress=0.5, steps=3) + assert render("ping-auto-table") != render("ping-mac-table", table="mac") + assert render("default") == render("ping-end", scenario="ping", progress=1.0) + trace = {"scenario": "traceroute", "topology": "single-switch"} + trace_auto = render("trace-auto-table", **trace) + assert trace_auto == render("trace-mac-table", table="mac", **trace) + assert trace_auto != render("trace-route-table", table="route", **trace) + render("invalid-scenario", scenario="ospf", expect_error=True) + render("invalid-topology", topology="token-ring", expect_error=True) + + clip["animations"] = [{"target": {"Param": "progress"}, "keys": { + "0": {"value": {"Number": 0.0}, "interpolation": "Linear"}, + "705600000": {"value": {"Number": 1.0}, "interpolation": "Hold"}, + }}] + assert midpoint == render("tcp-keyframed-midpoint", frame=15, scenario="tcp", progress=0) + clip["animations"] = [] + print("PASS default frame, exact PNG repeat, parameter changes, diagnostic and host keyframes") + + project["width"], project["height"] = 480, 720 + render("portrait", scenario="dns", progress=0.7, labels="brief", table="route") + project["width"], project["height"] = 1280, 720 + if args.screenshots: + out = ROOT / "screenshots" + out.mkdir(exist_ok=True) + single = {"topology": "single-switch"} + shots = { + "ping": dict(scenario="ping", progress=9 / 12.75), + "arp-flood": dict(scenario="arp", progress=2 / 8.75, **single), + "arp-cache": dict(scenario="arp", progress=5 / 8.75, table="arp", **single), + "tcp": dict(scenario="tcp", progress=5 / 24.75), + "dhcp": dict(scenario="dhcp", progress=6 / 8.75, **single), + "dns": dict(scenario="dns", progress=10 / 14.75), + "traceroute": dict(scenario="traceroute", progress=7 / 10.75), + } + for name, params in shots.items(): + (out / f"{name}.png").write_bytes(render(f"screenshot-{name}", **params)) + print(f"SAVED {name}.png") + + +if __name__ == "__main__": + main() diff --git a/community/network/src/draw.rs b/community/network/src/draw.rs new file mode 100644 index 0000000..bdaa3d5 --- /dev/null +++ b/community/network/src/draw.rs @@ -0,0 +1,1344 @@ +//! Scene drawing: topology glyphs, packets in flight, panels. All geometry is +//! computed from the canvas size, so output is resolution-independent and a pure +//! function of (params, timeline position). + +use super::scenario::{Event, Proto, Scenario, TableKind}; +use super::tables::TableState; +use super::timeline; +use super::topology::{DeviceKind, Topology, CLIENT}; +use crate::animathio::plugin::types::{ + Color, CoordinateSpace, DrawCommand, PathVerb, Point, Scene, Size, StrokeCap, StrokeJoin, + StrokeStyle, TextAlignment, TextElement, +}; + +// Palette (dark teaching board). +const TEXT_BRIGHT: Color = Color { + r: 235, + g: 240, + b: 245, + a: 255, +}; +const TEXT_DIM: Color = Color { + r: 158, + g: 176, + b: 189, + a: 255, +}; +const LINK_COLOR: Color = Color { + r: 91, + g: 112, + b: 128, + a: 255, +}; +const DEVICE_FILL: Color = Color { + r: 30, + g: 41, + b: 54, + a: 255, +}; +const DEVICE_STROKE: Color = Color { + r: 168, + g: 190, + b: 205, + a: 255, +}; +const PANEL_BG: Color = Color { + r: 17, + g: 24, + b: 33, + a: 240, +}; +const PANEL_STROKE: Color = Color { + r: 52, + g: 67, + b: 82, + a: 255, +}; +const PACKET_EDGE: Color = Color { + r: 12, + g: 18, + b: 24, + a: 255, +}; +const PORT_TEXT: Color = Color { + r: 130, + g: 148, + b: 162, + a: 255, +}; +const PACKET_TEXT_DARK: Color = Color { + r: 20, + g: 26, + b: 32, + a: 255, +}; +const PACKET_TEXT_LIGHT: Color = Color { + r: 246, + g: 250, + b: 252, + a: 255, +}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Labels { + Full, + Brief, + None, +} + +pub struct DrawInput<'a> { + pub topo: &'static Topology, + pub events: &'a [Event], + pub scenario: Scenario, + /// Timeline position (event slots) from `timeline::position`. + pub u: f32, + pub labels: Labels, + pub table_kind: TableKind, + pub show_tables: bool, + pub show_step_list: bool, + pub speed_lines: bool, + /// Packet glyph size as a percentage of the short canvas edge (0.5..6). + pub packet_percent: f32, + pub accent: Color, +} + +struct Painter { + elements: Vec, + width: f32, +} + +impl Painter { + fn new(width: f32) -> Self { + Self { + elements: Vec::new(), + width, + } + } + + fn with_alpha(mut color: Color, alpha: f32) -> Color { + color.a = ((color.a as f32) * alpha.clamp(0.0, 1.0)).round() as u8; + color + } + + fn rounded_rect(x: f32, y: f32, w: f32, h: f32, r: f32) -> Vec { + let r = r.max(0.0).min(w * 0.5).min(h * 0.5); + let k = 0.552_284_8 * r; + let p = |px: f32, py: f32| Point { x: px, y: py }; + vec![ + PathVerb::MoveTo(p(x + r, y)), + PathVerb::LineTo(p(x + w - r, y)), + PathVerb::CubicTo((p(x + w - r + k, y), p(x + w, y + r - k), p(x + w, y + r))), + PathVerb::LineTo(p(x + w, y + h - r)), + PathVerb::CubicTo(( + p(x + w, y + h - r + k), + p(x + w - r + k, y + h), + p(x + w - r, y + h), + )), + PathVerb::LineTo(p(x + r, y + h)), + PathVerb::CubicTo((p(x + r - k, y + h), p(x, y + h - r + k), p(x, y + h - r))), + PathVerb::LineTo(p(x, y + r)), + PathVerb::CubicTo((p(x, y + r - k), p(x + r - k, y), p(x + r, y))), + PathVerb::Close, + ] + } + + fn fill(&mut self, path: Vec, color: Color) { + if color.a == 0 { + return; + } + self.elements.push(DrawCommand::FillPath((path, color))); + } + + fn fill_round(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, color: Color) { + if w <= 0.0 || h <= 0.0 || color.a == 0 { + return; + } + self.fill(Self::rounded_rect(x, y, w, h, r), color); + } + + fn stroke(&mut self, path: Vec, width: f32, color: Color) { + if color.a == 0 || width <= 0.0 { + return; + } + self.elements.push(DrawCommand::StrokePath(( + path, + StrokeStyle { + width, + color, + cap: StrokeCap::Round, + join: StrokeJoin::Round, + }, + ))); + } + + #[allow(clippy::too_many_arguments)] // (x, y, w, h, r) mirror `fill_round`. + fn stroke_round(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, width: f32, color: Color) { + if w <= 0.0 || h <= 0.0 || color.a == 0 || width <= 0.0 { + return; + } + self.stroke(Self::rounded_rect(x, y, w, h, r), width, color); + } + + fn line(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, width: f32, color: Color) { + if color.a == 0 || width <= 0.0 { + return; + } + self.stroke( + vec![ + PathVerb::MoveTo(Point { x: x1, y: y1 }), + PathVerb::LineTo(Point { x: x2, y: y2 }), + ], + width, + color, + ); + } + + fn fill_circle(&mut self, cx: f32, cy: f32, r: f32, color: Color) { + if color.a == 0 || r <= 0.0 { + return; + } + let k = 0.552_284_8 * r; + let p = |dx: f32, dy: f32| Point { + x: cx + dx, + y: cy + dy, + }; + let path = vec![ + PathVerb::MoveTo(p(r, 0.0)), + PathVerb::CubicTo((p(r, k), p(k, r), p(0.0, r))), + PathVerb::CubicTo((p(-k, r), p(-r, k), p(-r, 0.0))), + PathVerb::CubicTo((p(-r, -k), p(-k, -r), p(0.0, -r))), + PathVerb::CubicTo((p(k, -r), p(r, -k), p(r, 0.0))), + PathVerb::Close, + ]; + self.fill(path, color); + } + + fn dashed_circle(&mut self, cx: f32, cy: f32, r: f32, width: f32, color: Color) { + if color.a == 0 || r <= 0.0 { + return; + } + let segments = 24; + let step = std::f32::consts::TAU / (segments as f32); + for i in 0..segments { + if i % 2 == 1 { + continue; + } + let a0 = i as f32 * step; + let a1 = a0 + step; + self.line( + cx + r * a0.cos(), + cy + r * a0.sin(), + cx + r * a1.cos(), + cy + r * a1.sin(), + width, + color, + ); + } + } + + /// Horizontal arrow with a solid triangular head. + fn arrow(&mut self, x1: f32, y: f32, x2: f32, head: f32, width: f32, color: Color) { + self.line(x1, y, x2, y, width, color); + let dir = (x2 - x1).signum(); + let path = vec![ + PathVerb::MoveTo(Point { + x: x2 - dir * head * 0.6, + y: y - head, + }), + PathVerb::LineTo(Point { + x: x2 + dir * head, + y, + }), + PathVerb::LineTo(Point { + x: x2 - dir * head * 0.6, + y: y + head, + }), + PathVerb::Close, + ]; + self.fill(path, color); + } + + /// The released host aligns a canvas text run within the canvas width. + fn text_center(&mut self, text: &str, cx: f32, baseline: f32, font: f32, color: Color) { + if text.is_empty() || color.a == 0 || font <= 0.0 { + return; + } + self.elements.push(DrawCommand::TextRun(TextElement { + align: TextAlignment::Center, + text: text.to_string(), + font_size: font, + x: cx - self.width * 0.5, + y: baseline - font * 0.93, + color, + })); + } + + fn text_left(&mut self, text: &str, x: f32, baseline: f32, font: f32, color: Color) { + if text.is_empty() || color.a == 0 || font <= 0.0 { + return; + } + self.elements.push(DrawCommand::TextRun(TextElement { + align: TextAlignment::Left, + text: text.to_string(), + font_size: font, + x, + y: baseline - font * 0.93, + color, + })); + } +} + +fn lerp(a: f32, b: f32, t: f32) -> f32 { + a + (b - a) * t +} + +/// Truncate to `max_chars` characters with an ellipsis (deterministic). +fn truncate(text: &str, max_chars: usize) -> String { + if text.chars().count() <= max_chars { + return text.to_string(); + } + let mut out: String = text.chars().take(max_chars.saturating_sub(1)).collect(); + out.push('…'); + out +} + +fn proto_color(proto: Proto) -> Color { + let (r, g, b) = proto.rgba(); + Color { r, g, b, a: 255 } +} + +#[derive(Clone, Copy, Debug)] +struct Rect { + x: f32, + y: f32, + w: f32, + h: f32, +} + +impl Rect { + fn centered(x: f32, y: f32, w: f32, h: f32) -> Self { + Self { + x: x - w * 0.5, + y: y - h * 0.5, + w, + h, + } + } + + fn padded(self, pad: f32) -> Self { + Self { + x: self.x - pad, + y: self.y - pad, + w: self.w + 2.0 * pad, + h: self.h + 2.0 * pad, + } + } + + fn overlaps(self, other: Self) -> bool { + self.x < other.right() + && other.x < self.right() + && self.y < other.bottom() + && other.y < self.bottom() + } + + fn contains(self, other: Self) -> bool { + self.x <= other.x + && self.y <= other.y + && self.right() >= other.right() + && self.bottom() >= other.bottom() + } + + fn right(self) -> f32 { + self.x + self.w + } + + fn bottom(self) -> f32 { + self.y + self.h + } +} + +/// One content row of the table panel: two columns plus the event index that +/// inserted it (drives the "just learned" highlight). +struct TableRow { + left: String, + right: String, + at: Option, +} + +fn empty_row(label: &str) -> TableRow { + TableRow { + left: label.to_string(), + right: String::new(), + at: None, + } +} + +/// Table panel content for the effective table kind. +fn table_rows(input: &DrawInput, state: &TableState) -> (&'static str, Vec) { + let kind = match input.table_kind { + TableKind::Auto => input.scenario.auto_table(input.topo), + other => other, + }; + match kind { + TableKind::Arp => { + let rows = if state.arp.is_empty() { + vec![empty_row("Waiting for a frame")] + } else { + state + .arp + .iter() + .map(|r| TableRow { + left: r.ip.to_string(), + right: r.mac.to_string(), + at: Some(r.at), + }) + .collect() + }; + ("PC1 ARP cache", rows) + } + TableKind::Route => { + let rows = if input.topo.routes.is_empty() { + vec![empty_row("No router on this LAN")] + } else { + input + .topo + .routes + .iter() + .map(|r| TableRow { + left: r.destination.to_string(), + right: format!("{} · {}", r.kind, r.interface), + at: None, + }) + .collect() + }; + ("Router routing table", rows) + } + _ => { + let rows = if state.mac.is_empty() { + vec![empty_row("Waiting for a frame")] + } else { + state + .mac + .iter() + .map(|r| TableRow { + left: r.port.to_string(), + right: r.mac.to_string(), + at: Some(r.at), + }) + .collect() + }; + ("Switch MAC table", rows) + } + } +} + +fn panel(p: &mut Painter, rect: Rect, short: f32) { + let Rect { x, y, w, h } = rect; + p.fill_round(x, y, w, h, 0.012 * short, PANEL_BG); + p.stroke_round( + x, + y, + w, + h, + 0.012 * short, + (0.0018 * short).max(1.0), + PANEL_STROKE, + ); +} + +fn glyph_body(cx: f32, cy: f32, kind: DeviceKind, icon: f32) -> (Rect, f32) { + let (width, height, center_y, corners) = match kind { + DeviceKind::Host => (0.92, 0.64, -0.14, 0.07), + DeviceKind::Switch => (1.20, 0.44, 0.0, 0.09), + DeviceKind::Router => (1.10, 0.84, 0.0, 0.20), + DeviceKind::Server => (0.68, 1.08, 0.0, 0.08), + }; + ( + Rect::centered(cx, cy + center_y * icon, width * icon, height * icon), + corners * icon, + ) +} + +fn glyph_stroke(short: f32) -> f32 { + (0.004 * short).max(1.0) +} + +fn glyph_bounds(cx: f32, cy: f32, kind: DeviceKind, icon: f32, short: f32) -> Rect { + let (body, _) = glyph_body(cx, cy, kind, icon); + let mut bounds = body.padded(glyph_stroke(short) * 0.5); + if kind == DeviceKind::Host { + // Include the monitor stand and the round cap of its base. + bounds.h = bounds.h.max(cy + (0.34 + 0.035 / 2.0) * icon - bounds.y); + } + bounds +} + +/// Vector device glyph, drawn from scratch (original artwork; see NOTICE). +fn glyph(p: &mut Painter, cx: f32, cy: f32, kind: DeviceKind, s: f32, short: f32, accent: Color) { + let (body, corners) = glyph_body(cx, cy, kind, s); + let Rect { x, y, w, h } = body; + p.fill_round(x, y, w, h, corners, DEVICE_FILL); + p.stroke_round(x, y, w, h, corners, glyph_stroke(short), DEVICE_STROKE); + match kind { + DeviceKind::Host => { + p.fill_round( + cx - 0.11 * s, + cy + 0.18 * s, + 0.22 * s, + 0.16 * s, + 0.02 * s, + DEVICE_FILL, + ); + p.line( + cx - 0.30 * s, + cy + 0.34 * s, + cx + 0.30 * s, + cy + 0.34 * s, + 0.035 * s, + DEVICE_STROKE, + ); + } + DeviceKind::Switch => { + p.arrow( + cx - 0.40 * s, + cy - 0.10 * s, + cx + 0.34 * s, + 0.07 * s, + 0.020 * s, + Painter::with_alpha(accent, 0.95), + ); + p.arrow( + cx + 0.40 * s, + cy + 0.12 * s, + cx - 0.34 * s, + 0.07 * s, + 0.020 * s, + Painter::with_alpha(accent, 0.70), + ); + } + DeviceKind::Router => { + p.arrow( + cx - 0.36 * s, + cy - 0.16 * s, + cx + 0.30 * s, + 0.08 * s, + 0.022 * s, + Painter::with_alpha(accent, 0.95), + ); + p.arrow( + cx + 0.36 * s, + cy + 0.16 * s, + cx - 0.30 * s, + 0.08 * s, + 0.022 * s, + Painter::with_alpha(accent, 0.70), + ); + } + DeviceKind::Server => { + p.line( + cx - 0.20 * s, + cy - 0.30 * s, + cx + 0.20 * s, + cy - 0.30 * s, + 0.012 * s, + Painter::with_alpha(DEVICE_STROKE, 0.55), + ); + p.line( + cx - 0.20 * s, + cy - 0.12 * s, + cx + 0.20 * s, + cy - 0.12 * s, + 0.012 * s, + Painter::with_alpha(DEVICE_STROKE, 0.55), + ); + p.fill_circle( + cx + 0.16 * s, + cy + 0.28 * s, + 0.04 * s, + Painter::with_alpha(accent, 0.95), + ); + } + } +} + +/// Visual knobs of a packet glyph, bundled to keep `packet` readable. +struct PacketStyle { + labels: Labels, + speed_lines: bool, + /// Glyph size in canvas pixels. + base: f32, + short: f32, +} + +fn packet_style(input: &DrawInput, rect: Rect, short: f32) -> PacketStyle { + PacketStyle { + labels: input.labels, + speed_lines: input.speed_lines, + base: (short * input.packet_percent / 100.0).min(rect.w * 0.06), + short, + } +} + +struct Packet { + px: f32, + py: f32, + radius: f32, + plate: Option, + label: String, + font: f32, +} + +fn packet_geometry( + (ax, ay): (f32, f32), + (bx, by): (f32, f32), + t: f32, + event: &Event, + style: &PacketStyle, +) -> Packet { + let px = lerp(ax, bx, t); + let py = lerp(ay, by, t); + if style.labels == Labels::None { + return Packet { + px, + py, + radius: style.base * 0.62, + plate: None, + label: String::new(), + font: 0.0, + }; + } + + let radius = style.base * 0.34; + let base = if style.labels == Labels::Full { + event.proto.full() + } else { + event.proto.short() + }; + let label = match event.ttl { + Some(ttl) => format!("{base} · TTL {ttl}"), + None => base.to_string(), + }; + let font = style.base.min(style.short * 0.034) * 0.68; + let width = (label.chars().count() as f32 * 0.62 + 1.5) * font; + let height = font * 2.04; + let bottom = py - radius - style.short * 0.007; + Packet { + px, + py, + radius, + plate: Some(Rect::centered(px, bottom - height * 0.5, width, height)), + label, + font, + } +} + +fn packet_rim(short: f32) -> f32 { + short * 0.0016 +} + +/// One packet glyph (possibly with speed lines) travelling `from → leg`. +fn packet( + p: &mut Painter, + (ax, ay): (f32, f32), + (bx, by): (f32, f32), + t: f32, + proto: Proto, + style: &PacketStyle, + shape: &Packet, +) { + let fill = proto_color(proto); + if style.speed_lines && t > 0.14 { + let (t0, t1, t2) = ( + (t - 0.16).max(0.0), + (t - 0.05).max(0.0), + (t - 0.028).max(0.0), + ); + p.line( + lerp(ax, bx, t0), + lerp(ay, by, t0), + lerp(ax, bx, t1), + lerp(ay, by, t1), + style.short * 0.003, + Painter::with_alpha(fill, 0.35), + ); + p.line( + lerp(ax, bx, t1), + lerp(ay, by, t1), + lerp(ax, bx, t2), + lerp(ay, by, t2), + style.short * 0.002, + Painter::with_alpha(fill, 0.22), + ); + } + let (px, py) = (shape.px, shape.py); + let edge = packet_rim(style.short); + p.fill_circle(px, py, shape.radius + edge, PACKET_EDGE); + p.fill_circle(px, py, shape.radius, fill); + let Some(plate) = shape.plate else { + return; + }; + p.fill_round( + plate.x, + plate.y, + plate.w, + plate.h, + plate.h * 0.30, + PACKET_EDGE, + ); + p.fill_round( + plate.x + edge, + plate.y + edge, + plate.w - edge * 2.0, + plate.h - edge * 2.0, + plate.h * 0.26, + Painter::with_alpha(fill, 0.94), + ); + let (r, g, b) = proto.rgba(); + let luminance = (0.299 * f32::from(r) + 0.587 * f32::from(g) + 0.114 * f32::from(b)) / 255.0; + let text = if luminance > 0.62 { + PACKET_TEXT_DARK + } else { + PACKET_TEXT_LIGHT + }; + p.text_center( + &shape.label, + px, + plate.y + plate.h * 0.5 + shape.font * 0.36, + shape.font, + text, + ); +} + +fn text_fit( + p: &mut Painter, + text: &str, + x: f32, + baseline: f32, + font: f32, + width: f32, + color: Color, +) { + let chars = (width / (font * 0.59)).floor().max(1.0) as usize; + p.text_left(&truncate(text, chars), x, baseline, font, color); +} + +struct DiagramMetrics { + icon: f32, + em: f32, + tick: f32, + port_font: f32, +} + +fn device_centers(topo: &Topology, rect: Rect) -> Vec<(f32, f32)> { + topo.anchors + .iter() + .map(|&(x, y)| (rect.x + x * rect.w, rect.y + y * rect.h)) + .collect() +} + +fn diagram_metrics(rect: Rect, short: f32) -> DiagramMetrics { + let icon = (short * 0.112).min(rect.w * 0.14).min(rect.h * 0.19); + let em = (short * 0.025).min(rect.w * 0.032); + DiagramMetrics { + icon, + em, + tick: icon * 0.11, + port_font: em * 0.67, + } +} + +struct LinkTicks { + a: (f32, f32), + b: (f32, f32), + along: (f32, f32), + normal: (f32, f32), + label_travel: f32, +} + +fn link_ticks((ax, ay): (f32, f32), (bx, by): (f32, f32), icon: f32) -> LinkTicks { + let (dx, dy) = (bx - ax, by - ay); + let len = dx.hypot(dy); + let (ux, uy) = (dx / len.max(f32::EPSILON), dy / len.max(f32::EPSILON)); + let inset = (icon * 0.68).min(len * 0.35); + // The pill sits above the wire. Put labels below it, or to the right + // when the wire runs vertically. + let normal = if dx == 0.0 { + (1.0, 0.0) + } else { + (-uy * dx.signum(), ux.abs()) + }; + LinkTicks { + a: (ax + ux * inset, ay + uy * inset), + b: (bx - ux * inset, by - uy * inset), + along: (ux, uy), + normal, + label_travel: len * 0.49 - inset, + } +} + +fn port_label_bounds(label: &str, x: f32, baseline: f32, font: f32) -> Rect { + // Allow for the host's text metrics and antialiasing. + let width = label.chars().count() as f32 * 0.62 * font; + Rect::centered(x, baseline - font * 0.325, width, font * 1.35).padded(font * 0.2) +} + +fn place_port_label( + tick: (f32, f32), + toward: f32, + ticks: &LinkTicks, + text: &str, + font: f32, + diagram: Rect, + obstacles: &[Rect], +) -> Option<(f32, f32, Rect)> { + let (tx, ty) = tick; + let (nx, ny) = ticks.normal; + let (ux, uy) = ticks.along; + let bounds = port_label_bounds(text, 0.0, 0.0, font); + let clearance = (nx.abs() * bounds.w + ny.abs() * bounds.h) * 0.5 + font * 0.8; + + // Stay near the tick, moving along the wire before moving farther away. + // Either side of a vertical link can clear the pill above the packet. + let sides: &[f32] = if ux == 0.0 { &[1.0, -1.0] } else { &[1.0] }; + let nudges = [0, 1, 2, 3, 4, 5, 6, -1, -2, -3, -4]; + let step = ticks.label_travel.min(font * 6.0) / 6.0; + for offset in 0..=6 { + for &side in sides { + let away = side * (clearance + offset as f32 * font * 0.75); + for nudge in nudges { + let along = nudge as f32 * step * toward; + let x = tx + nx * away + ux * along; + let baseline = ty + ny * away + uy * along + font * 0.325; + let bounds = port_label_bounds(text, x, baseline, font); + if diagram.contains(bounds) + && !obstacles.iter().any(|obstacle| bounds.overlaps(*obstacle)) + { + return Some((x, baseline, bounds)); + } + } + } + } + None +} + +fn packet_obstacles(packet: &Packet, short: f32) -> impl Iterator { + let diameter = (packet.radius + packet_rim(short)) * 2.0; + let dot = Rect::centered(packet.px, packet.py, diameter, diameter); + std::iter::once(dot).chain(packet.plate) +} + +fn draw_diagram( + p: &mut Painter, + input: &DrawInput, + rect: Rect, + active: Option<(&Event, f32)>, + leased: bool, + short: f32, +) { + panel(p, rect, short); + let centers = device_centers(input.topo, rect); + let metrics = diagram_metrics(rect, short); + let style = packet_style(input, rect, short); + let mut obstacles = Vec::new(); + if input.labels == Labels::Full { + obstacles.extend( + input + .topo + .devices + .iter() + .zip(¢ers) + .map(|(device, &(cx, cy))| glyph_bounds(cx, cy, device.kind, metrics.icon, short)), + ); + } + let mut packets = Vec::new(); + if let Some((event, phase)) = active { + let from = centers[usize::from(event.from)]; + for &leg in &event.legs { + let to = centers[usize::from(leg)]; + let shape = packet_geometry(from, to, phase, event, &style); + if input.labels == Labels::Full { + obstacles.extend(packet_obstacles(&shape, short)); + } + packets.push((from, to, shape)); + } + } + for link in input.topo.links { + let (ax, ay) = centers[usize::from(link.a)]; + let (bx, by) = centers[usize::from(link.b)]; + let active_link = active.filter(|(event, _)| { + (event.from == link.a && event.legs.contains(&link.b)) + || (event.from == link.b && event.legs.contains(&link.a)) + }); + let (width, color) = if let Some((event, _)) = active_link { + (0.0035, Painter::with_alpha(proto_color(event.proto), 0.68)) + } else { + (0.0021, LINK_COLOR) + }; + p.line(ax, ay, bx, by, width * short, color); + let ticks = link_ticks((ax, ay), (bx, by), metrics.icon); + for (tick, text, toward) in [(ticks.a, link.a_port, 1.0), (ticks.b, link.b_port, -1.0)] { + let (tx, ty) = tick; + p.fill_round( + tx - metrics.tick / 2.0, + ty - metrics.tick / 2.0, + metrics.tick, + metrics.tick, + metrics.tick * 0.25, + color, + ); + if input.labels == Labels::Full { + let font = metrics.port_font; + if let Some((x, baseline, bounds)) = + place_port_label(tick, toward, &ticks, text, font, rect, &obstacles) + { + p.text_center(text, x, baseline, font, PORT_TEXT); + obstacles.push(bounds); + } + } + } + } + + if let Some((event, phase)) = active { + if event.broadcast { + let (cx, cy) = centers[usize::from(event.from)]; + let radius = lerp(0.58, 1.45, phase) * metrics.icon; + p.dashed_circle( + cx, + cy, + radius, + short * 0.0026, + Painter::with_alpha(proto_color(event.proto), (1.0 - phase) * 0.70), + ); + } + } + + for (i, device) in input.topo.devices.iter().enumerate() { + let (cx, cy) = centers[i]; + let facing = input.topo.label_above[i]; + glyph(p, cx, cy, device.kind, metrics.icon, short, input.accent); + let (name_y, ip_y) = if facing { + let name_y = cy - metrics.icon * 0.58 - metrics.em * 0.7; + (name_y, name_y - metrics.em * 1.13) + } else { + let name_y = cy + metrics.icon * 0.61 + metrics.em * 0.85; + (name_y, name_y + metrics.em * 1.06) + }; + p.text_center(device.name, cx, name_y, metrics.em, TEXT_BRIGHT); + let address = if i == usize::from(CLIENT) && input.scenario == Scenario::Dhcp && !leased { + "Awaiting lease" + } else { + device.ip + }; + if input.labels != Labels::None { + p.text_center(address, cx, ip_y, metrics.em * 0.78, TEXT_DIM); + } + } + + if let Some((event, phase)) = active { + for (from, to, shape) in &packets { + packet(p, *from, *to, phase, event.proto, &style, shape); + } + } +} + +fn draw_table( + p: &mut Painter, + rect: Rect, + title: &str, + rows: &[TableRow], + done: usize, + em: f32, + short: f32, +) { + panel(p, rect, short); + let pad = em * 0.9; + let x = rect.x + pad; + p.text_left(title, x, rect.y + pad + em * 0.78, em, TEXT_BRIGHT); + let divider = rect.y + pad + em * 1.4; + p.line( + x, + divider, + rect.right() - pad, + divider, + short * 0.0014, + PANEL_STROKE, + ); + for (i, row) in rows.iter().enumerate() { + let y = divider + em * (1.28 + i as f32 * 1.25); + let highlighted = row.at.is_some_and(|at| at + 1 == done); + let left_x = x + em * 0.55; + if highlighted { + p.fill_circle(x + em * 0.10, y - em * 0.35, em * 0.13, TEXT_BRIGHT); + } + let font = em * 0.90; + let split = rect.x + rect.w * 0.43; + let max_left = if row.right.is_empty() { + rect.right() - pad + } else { + split - pad + }; + text_fit( + p, + &row.left, + left_x, + y, + font, + max_left - left_x, + TEXT_BRIGHT, + ); + text_fit( + p, + &row.right, + split, + y, + font, + rect.right() - pad - split, + TEXT_DIM, + ); + } +} + +fn draw_steps( + p: &mut Painter, + input: &DrawInput, + rect: Rect, + done: usize, + active: Option, + em: f32, + short: f32, +) { + panel(p, rect, short); + let pad = em * 0.88; + let x = rect.x + pad; + let divider = rect.y + pad + em * 1.65; + let row_h = em * 2.48; + let count = input.events.len(); + let selected = active.unwrap_or_else(|| done.saturating_sub(1)); + let visible = (((rect.bottom() - divider - pad) / row_h) as usize).clamp(1, count); + let start = selected.saturating_sub(visible / 2).min(count - visible); + let heading = if done == count { + format!("{count}/{count} steps shown") + } else if active.is_none() { + format!("{count} steps · Ready") + } else { + format!("Step {} of {count}", selected + 1) + }; + p.text_left(&heading, x, rect.y + pad + em * 0.83, em, TEXT_BRIGHT); + p.line( + x, + divider, + rect.right() - pad, + divider, + short * 0.0014, + PANEL_STROKE, + ); + + let col = x + em * 1.85; + let max_width = rect.right() - pad - col; + for (i, event) in input.events.iter().enumerate().skip(start).take(visible) { + let y = divider + em * 0.28 + (i - start) as f32 * row_h; + let current = active == Some(i); + if current { + p.fill_round( + rect.x + pad * 0.4, + y, + rect.w - pad * 0.8, + row_h, + em * 0.34, + Painter::with_alpha(input.accent, 0.15), + ); + p.fill_round( + rect.x + pad * 0.4, + y + em * 0.36, + em * 0.14, + row_h - em * 0.72, + em * 0.07, + input.accent, + ); + } + let label = if input.labels == Labels::Brief { + event.proto.short() + } else { + event.proto.full() + }; + let title = if let Some(ttl) = event.ttl { + format!("{label} · TTL {ttl}") + } else { + label.into() + }; + let baseline = y + em * 1.05; + let event_color = if i < done { TEXT_DIM } else { TEXT_BRIGHT }; + p.text_left(&(i + 1).to_string(), x, baseline, em * 0.80, event_color); + text_fit(p, &title, col, baseline, em * 0.95, max_width, event_color); + let devices = input.topo.devices; + let peer_names = event + .legs + .iter() + .map(|&leg| devices[usize::from(leg)].name) + .collect::>() + .join(", "); + let path = format!("{} → {peer_names}", devices[usize::from(event.from)].name); + let note = if input.labels == Labels::Full && !event.note.is_empty() { + &event.note + } else { + &path + }; + text_fit(p, note, col, y + em * 2.04, em * 0.76, max_width, TEXT_DIM); + } +} + +struct Layout { + area: Rect, + diagram: Rect, + step_w: f32, + step_h: f32, + table_h: f32, + em: f32, + margin: f32, + gap: f32, +} + +fn layout(input: &DrawInput, w: f32, h: f32) -> Layout { + let short = w.min(h); + let em = short * 0.026; + let margin = short * 0.035; + let gap = short * 0.021; + let title_h = em * 3.2; + let area = Rect { + x: margin, + y: margin + title_h, + w: w - 2.0 * margin, + h: h - 2.0 * margin - title_h, + }; + let beside = w / h >= 1.24; + let step_w = if beside && input.show_step_list { + area.w * 0.34 + } else { + 0.0 + }; + let step_h = if !beside && input.show_step_list { + area.h * 0.44 + } else { + 0.0 + }; + let table_h = if input.show_tables { em * 7.65 } else { 0.0 }; + let left_w = area.w - if step_w > 0.0 { step_w + gap } else { 0.0 }; + let diagram_h = area.h + - if step_h > 0.0 { step_h + gap } else { 0.0 } + - if table_h > 0.0 { table_h + gap } else { 0.0 }; + Layout { + area, + diagram: Rect { + w: left_w, + h: diagram_h, + ..area + }, + step_w, + step_h, + table_h, + em, + margin, + gap, + } +} + +pub fn draw(input: &DrawInput, size: &Size) -> Scene { + let (w, h) = (size.width as f32, size.height as f32); + let short = w.min(h); + let layout = layout(input, w, h); + let em = layout.em; + let margin = layout.margin; + let gap = layout.gap; + let done = timeline::done(input.u); + let playing = timeline::playing(input.u, input.events.len()); + let active = playing + .zip(timeline::phase(input.u, input.events.len())) + .map(|(i, phase)| (&input.events[i], phase)); + let state = super::tables::replay(input.events, done); + let (table_title, rows) = table_rows(input, &state); + + let mut p = Painter::new(w); + + p.fill_round( + 0.0, + 0.0, + w, + h, + 0.0, + Color { + r: 12, + g: 18, + b: 27, + a: 255, + }, + ); + p.text_left( + input.scenario.title(), + margin, + margin + em * 1.47, + em * 1.7, + TEXT_BRIGHT, + ); + text_fit( + &mut p, + input.topo.label, + margin, + margin + em * 2.72, + em * 0.90, + layout.area.w, + TEXT_DIM, + ); + let leased = input + .events + .get(done.saturating_sub(1)) + .is_some_and(|event| { + done > 0 && event.proto == Proto::DhcpAck && event.legs.contains(&CLIENT) + }); + draw_diagram(&mut p, input, layout.diagram, active, leased, short); + if input.show_tables { + let rect = Rect { + y: layout.diagram.bottom() + gap, + h: layout.table_h, + ..layout.diagram + }; + draw_table(&mut p, rect, table_title, &rows, done, em, short); + } + if input.show_step_list { + let rect = if layout.step_w > 0.0 { + Rect { + x: layout.diagram.right() + gap, + w: layout.step_w, + ..layout.area + } + } else { + Rect { + y: layout.area.bottom() - layout.step_h, + h: layout.step_h, + ..layout.area + } + }; + draw_steps(&mut p, input, rect, done, playing, em, short); + } + Scene { + coordinate_space: CoordinateSpace::Canvas, + elements: p.elements, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::scenario::{build, SCENARIOS}; + use crate::topology::topology; + + #[test] + fn port_labels_clear_packets_and_devices() { + for routed in [false, true] { + for name in SCENARIOS { + let scenario = Scenario::parse(name).unwrap(); + let topo = topology(routed, scenario == Scenario::Dns); + let events = build(scenario, topo); + let mut input = DrawInput { + topo, + events: &events, + scenario, + u: 0.0, + labels: Labels::Full, + table_kind: TableKind::Auto, + show_tables: true, + show_step_list: true, + speed_lines: true, + packet_percent: 2.4, + accent: crate::ACCENT_DEFAULT, + }; + for (width, height) in [(1280, 720), (320, 180), (480, 720), (900, 900)] { + let size = Size { width, height }; + for (tables, steps) in + [(true, true), (true, false), (false, true), (false, false)] + { + input.show_tables = tables; + input.show_step_list = steps; + for packet_percent in [2.4, 6.0] { + input.packet_percent = packet_percent; + check_port_labels(&mut input, &size); + } + } + } + } + } + } + + fn check_port_labels(input: &mut DrawInput, size: &Size) { + let topo = input.topo; + let (w, h) = (size.width as f32, size.height as f32); + let short = w.min(h); + let diagram = layout(input, w, h).diagram; + let centers = device_centers(topo, diagram); + let icon = diagram_metrics(diagram, short).icon; + let devices: Vec<_> = topo + .devices + .iter() + .zip(¢ers) + .map(|(device, &(x, y))| glyph_bounds(x, y, device.kind, icon, short)) + .collect(); + let style = packet_style(input, diagram, short); + + // Include both holds and sample every hop, including each flood. + for sample in -1..=input.events.len() as i32 * 8 { + input.u = sample as f32 / 8.0; + let context = || { + format!( + "{:?} on {} at {w}x{h}, tables {}, steps {}, packet size {}, timeline position {}", + input.scenario, topo.label, input.show_tables, input.show_step_list, + input.packet_percent, input.u, + ) + }; + let mut obstacles = devices.clone(); + if let Some(index) = timeline::playing(input.u, input.events.len()) { + let event = &input.events[index]; + let from = centers[usize::from(event.from)]; + let phase = timeline::phase(input.u, input.events.len()).unwrap(); + for &leg in &event.legs { + let to = centers[usize::from(leg)]; + let shape = packet_geometry(from, to, phase, event, &style); + obstacles.extend(packet_obstacles(&shape, short)); + } + } + + let mut expected = topo.links.len() * 2; + if obstacles.len() > devices.len() { + // A moving pill may leave no clear spot close to the port. + expected -= 2; + } + let mut count = 0; + for element in draw(input, size).elements { + let DrawCommand::TextRun(run) = element else { + continue; + }; + if (run.color.r, run.color.g, run.color.b) + != (PORT_TEXT.r, PORT_TEXT.g, PORT_TEXT.b) + { + continue; + } + count += 1; + let bounds = port_label_bounds( + &run.text, + run.x + w * 0.5, + run.y + run.font_size * 0.93, + run.font_size, + ); + for obstacle in &obstacles { + // Recovering the anchor from the text run can round at the edge. + assert!( + !bounds.overlaps(obstacle.padded(-0.0001)), + "{}: {} {bounds:?} overlaps {obstacle:?}", + context(), + run.text, + ); + } + obstacles.push(bounds); + } + assert!(count >= expected, "{}: only {count} port labels", context()); + } + } +} diff --git a/community/network/src/lib.rs b/community/network/src/lib.rs new file mode 100644 index 0000000..95e66b1 --- /dev/null +++ b/community/network/src/lib.rs @@ -0,0 +1,125 @@ +//! Net Lab — deterministic, Packet Tracer-like networking animations as an +//! AniMathIO clip-source plugin. +//! +//! The render is a pure function of the parameters and `progress`: a small toy +//! topology plays a protocol scenario event by event (each event = one packet +//! crossing one link hop), while MAC/ARP/route tables fill in as a replay of the +//! events completed so far. Protocol sequencing studied in the MIT netsim +//! projects; all Rust code and all artwork are original — see NOTICE. + +wit_bindgen::generate!({ path: "wit", world: "source-plugin" }); +use animathio::plugin::types::*; + +mod draw; +mod params; +mod scenario; +mod tables; +#[cfg(test)] +mod tests; +mod timeline; +mod topology; + +use draw::{DrawInput, Labels}; +use params::{ + bool_param, boolean, color_of, color_param, enum_param, error, num_param, number, one_of, +}; +use scenario::{Scenario, TableKind, SCENARIOS, TABLES}; + +const ACCENT_DEFAULT: Color = Color { + r: 79, + g: 195, + b: 247, + a: 255, +}; +const TOPOLOGIES: [&str; 2] = ["single-switch", "through-router"]; + +struct NetLab; + +impl Guest for NetLab { + fn describe() -> Manifest { + Manifest { + name: "Net Lab".into(), + version: "1.0.0".into(), + description: + "Animate ARP, ICMP ping, TCP, DHCP, DNS and traceroute over teaching topologies" + .into(), + kinds: vec!["clip-source".into()], + metadata: vec![ + ("param.progress.unit".into(), "0..1 timeline".into()), + ("param.packet_size.unit".into(), "% of short edge".into()), + ], + params: vec![ + enum_param("scenario", "Scenario", &SCENARIOS, "ping"), + enum_param("topology", "Topology", &TOPOLOGIES, "through-router"), + num_param("progress", "Progress", 0.0, 1.0, 1.0, 0.01), + num_param("steps", "Steps (max events)", 1.0, 200.0, 24.0, 1.0), + enum_param("labels", "Labels", &["full", "brief", "none"], "full"), + bool_param("show_tables", "Show table panel", true), + enum_param("table", "Table", &TABLES, "auto"), + num_param("packet_size", "Packet size (%)", 0.5, 6.0, 2.4, 0.1), + color_param("accent", "Accent", ACCENT_DEFAULT), + bool_param("show_step_list", "Show step list", true), + bool_param("speed_lines", "Speed lines", true), + ], + } + } + + fn render_clip( + params: Vec, + _time_ticks: i64, + size: Size, + ) -> Result { + render(¶ms, size) + } +} + +fn render(params: &[ParamEntry], size: Size) -> Result { + if size.width == 0 || size.height == 0 { + return Err(error("Canvas dimensions must be positive")); + } + let scenario = Scenario::parse(one_of(params, "scenario", "ping", &SCENARIOS)?) + .ok_or_else(|| error("Unsupported scenario"))?; + let through_router = + one_of(params, "topology", "through-router", &TOPOLOGIES)? == "through-router"; + let topo = topology::topology(through_router, scenario == Scenario::Dns); + let labels = match one_of(params, "labels", "full", &["full", "brief", "none"])? { + "brief" => Labels::Brief, + "none" => Labels::None, + _ => Labels::Full, + }; + let table_kind = match one_of(params, "table", "auto", &TABLES)? { + "mac" => TableKind::Mac, + "arp" => TableKind::Arp, + "route" => TableKind::Route, + _ => TableKind::Auto, + }; + let progress = number(params, "progress", 1.0, 0.0, 1.0)?; + let steps = number(params, "steps", 24.0, 1.0, 200.0)? as usize; + let packet_percent = number(params, "packet_size", 2.4, 0.5, 6.0)?; + let show_tables = boolean(params, "show_tables", true); + let show_step_list = boolean(params, "show_step_list", true); + let speed_lines = boolean(params, "speed_lines", true); + let accent = color_of(params, "accent", ACCENT_DEFAULT); + + let mut events = scenario::build(scenario, topo); + events.truncate(steps); + let u = timeline::position(progress, events.len()); + Ok(draw::draw( + &DrawInput { + topo, + events: &events, + scenario, + u, + labels, + table_kind, + show_tables, + show_step_list, + speed_lines, + packet_percent, + accent, + }, + &size, + )) +} + +export!(NetLab); diff --git a/community/network/src/params.rs b/community/network/src/params.rs new file mode 100644 index 0000000..2ea1a78 --- /dev/null +++ b/community/network/src/params.rs @@ -0,0 +1,121 @@ +//! Shared parameter plumbing: readers with clamping defaults and schema helpers. + +use super::{ + BoolParam, Color, Diagnostic, EnumParam, NumberRange, ParamEntry, ParamKind, ParamSpec, + ParamValue, +}; + +pub fn error(message: &str) -> Diagnostic { + Diagnostic { + code: "invalid-input".into(), + message: message.into(), + metadata: vec![], + } +} + +pub fn number( + params: &[ParamEntry], + id: &str, + default: f64, + min: f64, + max: f64, +) -> Result { + let n = params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Number(n) => Some(n), + _ => None, + }) + .unwrap_or(default); + if !n.is_finite() { + return Err(error("Numeric parameters must be finite")); + } + Ok(n.clamp(min, max) as f32) +} + +pub fn boolean(params: &[ParamEntry], id: &str, default: bool) -> bool { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Bool(b) => Some(b), + _ => None, + }) + .unwrap_or(default) +} + +pub fn color_of(params: &[ParamEntry], id: &str, default: Color) -> Color { + params + .iter() + .find(|p| p.id == id) + .and_then(|p| match p.value { + ParamValue::Color(c) => Some(c), + _ => None, + }) + .unwrap_or(default) +} + +pub fn enum_param(id: &str, label: &str, options: &[&str], default: &str) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::EnumChoice(EnumParam { + options: options.iter().map(|s| (*s).into()).collect(), + default: default.into(), + }), + } +} + +pub fn num_param(id: &str, label: &str, min: f64, max: f64, default: f64, step: f64) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Number(NumberRange { + min, + max, + default, + step, + }), + } +} + +pub fn bool_param(id: &str, label: &str, default: bool) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Bool(BoolParam { default }), + } +} + +pub fn color_param(id: &str, label: &str, default: Color) -> ParamSpec { + ParamSpec { + id: id.into(), + label: label.into(), + kind: ParamKind::Color(crate::animathio::plugin::types::ColorParam { default }), + } +} + +/// One of a fixed option set, or an error naming the allowed values. A missing +/// parameter falls back to the default; an unsupported value *or a value of the +/// wrong type* fails with the same clear message. +pub fn one_of<'a>( + params: &'a [ParamEntry], + id: &str, + default: &'a str, + options: &[&str], +) -> Result<&'a str, Diagnostic> { + let value = match params.iter().find(|p| p.id == id).map(|p| &p.value) { + None => Some(default), + Some(ParamValue::String(s) | ParamValue::EnumChoice(s)) => Some(s.as_str()), + Some(_) => None, + }; + value + .filter(|value| options.contains(value)) + .ok_or_else(|| { + error(&format!( + "Unsupported {id}. Expected one of {}", + options.join(", ") + )) + }) +} diff --git a/community/network/src/scenario.rs b/community/network/src/scenario.rs new file mode 100644 index 0000000..b69613a --- /dev/null +++ b/community/network/src/scenario.rs @@ -0,0 +1,497 @@ +//! Protocol scenarios as ordered, per-hop event lists — the heart of the plugin. +//! +//! Every event moves one packet across exactly one link hop (`from` → `legs`); a +//! broadcast hop fans the frame out to every other port of the switch at once, the +//! way a real switch floods. Builders are pure functions of the topology choice and +//! follow the CCNA-textbook sequencing studied in the MIT netsim projects (see NOTICE). + +use super::tables::TableUpdate; +use super::topology::{Topology, CLIENT, PEER, SERVER}; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Proto { + ArpReq, + ArpReply, + Echo, + EchoReply, + TtlExceeded, + PortUnreachable, + Syn, + SynAck, + Ack, + Get, + Ok200, + Fin, + FinAck, + Discover, + Offer, + DhcpRequest, + DhcpAck, + DnsQuery, + DnsResponse, + Probe, +} + +impl Proto { + /// Text painted on the packet in `labels = brief` mode. + #[must_use] + pub fn short(self) -> &'static str { + match self { + Proto::ArpReq | Proto::ArpReply => "ARP", + Proto::Echo => "Echo", + Proto::EchoReply => "Reply", + Proto::TtlExceeded => "Expired", + Proto::PortUnreachable => "Port", + Proto::Syn => "SYN", + Proto::SynAck => "SYN-ACK", + Proto::Ack => "ACK", + Proto::Get => "GET", + Proto::Ok200 => "200 OK", + Proto::Fin => "FIN", + Proto::FinAck => "FIN-ACK", + Proto::Discover => "DISCOVER", + Proto::Offer => "OFFER", + Proto::DhcpRequest => "REQUEST", + Proto::DhcpAck => "ACK", + Proto::DnsQuery => "DNS?", + Proto::DnsResponse => "DNS!", + Proto::Probe => "UDP", + } + } + + /// Text painted on the packet in `labels = full` mode. + #[must_use] + pub fn full(self) -> &'static str { + match self { + Proto::ArpReq => "ARP Request", + Proto::ArpReply => "ARP Reply", + Proto::Echo => "Echo Request", + Proto::EchoReply => "Echo Reply", + Proto::TtlExceeded => "Time Exceeded", + Proto::PortUnreachable => "Port Unreachable", + Proto::Syn => "TCP SYN", + Proto::SynAck => "TCP SYN-ACK", + Proto::Ack => "TCP ACK", + Proto::Get => "HTTP GET", + Proto::Ok200 => "HTTP 200 OK", + Proto::Fin => "TCP FIN", + Proto::FinAck => "TCP FIN-ACK", + Proto::Discover => "DHCP Discover", + Proto::Offer => "DHCP Offer", + Proto::DhcpRequest => "DHCP Request", + Proto::DhcpAck => "DHCP ACK", + Proto::DnsQuery => "DNS Query", + Proto::DnsResponse => "DNS Response", + Proto::Probe => "UDP Probe", + } + } + + /// Packet fill color, stable per protocol family (orange ARP, blue ICMP, + /// green TCP/HTTP, purple DHCP, pink DNS, brown probes, red errors). + #[must_use] + pub fn rgba(self) -> (u8, u8, u8) { + match self { + Proto::ArpReq => (255, 167, 38), + Proto::ArpReply => (255, 213, 79), + Proto::Echo => (66, 165, 245), + Proto::EchoReply => (38, 198, 218), + Proto::TtlExceeded | Proto::PortUnreachable => (239, 83, 80), + Proto::Syn => (67, 160, 71), + Proto::SynAck => (102, 187, 106), + Proto::Ack => (129, 199, 132), + Proto::Get => (139, 195, 74), + Proto::Ok200 => (104, 159, 56), + Proto::Fin | Proto::FinAck => (156, 204, 101), + Proto::Discover | Proto::DhcpRequest => (126, 87, 194), + Proto::Offer | Proto::DhcpAck => (149, 117, 205), + Proto::DnsQuery => (236, 64, 122), + Proto::DnsResponse => (240, 98, 146), + Proto::Probe => (141, 110, 99), + } + } +} + +/// One packet crossing one link hop. Broadcast hops fan out to several legs at once. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct Event { + pub from: u8, + pub legs: Vec, + pub proto: Proto, + pub broadcast: bool, + pub ttl: Option, + /// Step-list explanation of this hop. + pub note: String, + /// Table entry learned when this hop completes. + pub table: Option, +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Scenario { + Ping, + Arp, + Tcp, + Dhcp, + Dns, + Traceroute, +} + +pub const SCENARIOS: [&str; 6] = ["ping", "arp", "tcp", "dhcp", "dns", "traceroute"]; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum TableKind { + Auto, + Mac, + Arp, + Route, +} + +pub const TABLES: [&str; 4] = ["auto", "mac", "arp", "route"]; + +impl Scenario { + #[must_use] + pub fn parse(value: &str) -> Option { + match value { + "ping" => Some(Self::Ping), + "arp" => Some(Self::Arp), + "tcp" => Some(Self::Tcp), + "dhcp" => Some(Self::Dhcp), + "dns" => Some(Self::Dns), + "traceroute" => Some(Self::Traceroute), + _ => None, + } + } + + #[must_use] + pub fn title(self) -> &'static str { + match self { + Self::Ping => "ICMP Ping", + Self::Arp => "ARP Resolution", + Self::Tcp => "TCP & HTTP", + Self::Dhcp => "DHCP DORA", + Self::Dns => "DNS Lookup", + Self::Traceroute => "Traceroute", + } + } + + /// Table the `auto` panel choice shows for this scenario. Traceroute only + /// shows routing where a router exists; a single-switch LAN falls back to + /// the switch's MAC table. + #[must_use] + pub fn auto_table(self, topo: &Topology) -> TableKind { + match self { + Self::Ping | Self::Dns => TableKind::Arp, + Self::Traceroute if !topo.routes.is_empty() => TableKind::Route, + _ => TableKind::Mac, + } + } +} + +/// Appends hops in wire order. Switch ingress learns a source, and a switch +/// egress floods when the destination MAC has yet to be learned. +struct Exchange<'a> { + topo: &'a Topology, + switch: u8, + learned: Vec, + events: Vec, +} + +impl Exchange<'_> { + fn hop(&mut self, from: u8, legs: Vec, proto: Proto, broadcast: bool, note: String) { + let table = if legs == [self.switch] && !self.learned.contains(&from) { + self.learned.push(from); + Some(TableUpdate::Mac { + port: self.topo.port_towards(self.switch, from), + mac: self.topo.mac_towards(from, self.switch), + device: from, + }) + } else { + None + }; + self.events.push(Event { + from, + legs, + proto, + broadcast, + ttl: None, + note, + table, + }); + } + + fn flood(&self, ingress: u8) -> Vec { + self.topo + .neighbors(self.switch) + .map(|(node, _)| node) + .filter(|&node| node != ingress) + .collect() + } + + fn broadcast_on_lan(&mut self, from: u8, proto: Proto, send: String, flood: &str) { + self.hop(from, vec![self.switch], proto, true, send); + self.hop(self.switch, self.flood(from), proto, true, flood.into()); + } + + fn send(&mut self, from: u8, to: u8, proto: Proto, note: impl Into) -> &mut [Event] { + let first = self.events.len(); + let path = self.topo.path(from, to); + let mut note = note.into(); + for (index, pair) in path.windows(2).enumerate() { + let (sender, receiver) = (pair[0], pair[1]); + if sender == self.switch && !self.learned.contains(&receiver) { + // An unknown destination floods the switch egress while the + // frame keeps its unicast address. + let legs = self.flood(path[index - 1]); + let explanation = if legs.len() == 1 { + "Unknown MAC: flood to the only other port" + } else { + "Unknown MAC: flood to every other port" + }; + self.hop(sender, legs, proto, false, explanation.into()); + } else { + self.hop( + sender, + vec![receiver], + proto, + false, + std::mem::take(&mut note), + ); + } + } + &mut self.events[first..] + } + + fn last(&mut self) -> &mut Event { + self.events.last_mut().expect("message contains a hop") + } + + fn resolve_on_lan(&mut self, target: u8) { + let target_ip = self.topo.devices[usize::from(target)].ip; + let mac = self.topo.mac_towards(target, self.switch); + self.broadcast_on_lan( + CLIENT, + Proto::ArpReq, + format!("Who has {target_ip}? Tell PC1"), + "Switch floods to every other port", + ); + self.send(target, CLIENT, Proto::ArpReply, format!("My MAC is {mac}")); + let arrival = self.last(); + arrival.note = format!("PC1 caches the MAC for {target_ip}"); + arrival.table = Some(TableUpdate::Arp { + device: CLIENT, + ip: target_ip, + mac, + }); + } + + fn ping(&mut self) { + let router = self.topo.router(); + self.resolve_on_lan(router.unwrap_or(SERVER)); + let target_ip = self.topo.devices[usize::from(SERVER)].ip; + if let Some(router) = router { + self.send( + CLIENT, + router, + Proto::Echo, + format!("Ping {target_ip} via the gateway"), + ); + self.hop( + router, + vec![SERVER], + Proto::ArpReq, + true, + format!("Router ARPs for {target_ip} on Gi0/1"), + ); + self.send(SERVER, router, Proto::ArpReply, "Server supplies its MAC"); + self.send( + router, + SERVER, + Proto::Echo, + "Router forwards the Echo Request", + ); + } else { + self.send( + CLIENT, + SERVER, + Proto::Echo, + format!("Ping {target_ip} on the same LAN"), + ); + } + self.echo_reply(SERVER); + } + + fn arp(&mut self) { + let target = self.topo.router().unwrap_or(PEER); + self.resolve_on_lan(target); + self.send( + CLIENT, + target, + Proto::Echo, + "Echo Request uses the cached MAC", + ); + self.echo_reply(target); + } + + fn echo_reply(&mut self, target: u8) { + self.send( + target, + CLIENT, + Proto::EchoReply, + "Destination sends an Echo Reply", + ); + self.last().note = "PC1 receives the Echo Reply".into(); + } + + fn tcp(&mut self) { + // The endpoints already know their next-hop MACs. The first SYN can + // still flood while the switch's own forwarding table is empty. + self.send(CLIENT, SERVER, Proto::Syn, "PC1 opens a TCP connection"); + self.send( + SERVER, + CLIENT, + Proto::SynAck, + "Server acknowledges and sends its SYN", + ); + self.send( + CLIENT, + SERVER, + Proto::Ack, + "PC1 acknowledges the server's SYN", + ); + self.last().note = "Server receives ACK: handshake complete".into(); + self.send(CLIENT, SERVER, Proto::Get, "GET /index.html"); + self.send(SERVER, CLIENT, Proto::Ok200, "Server returns the page"); + self.send(CLIENT, SERVER, Proto::Fin, "PC1 finishes sending"); + self.send( + SERVER, + CLIENT, + Proto::FinAck, + "Server acknowledges FIN and sends its own FIN", + ); + self.send( + CLIENT, + SERVER, + Proto::Ack, + "PC1 acknowledges the server's FIN", + ); + } + + fn dhcp(&mut self) { + let router = self.topo.router(); + let server = router.unwrap_or(SERVER); + let offer = if router.is_some() { + "Offers 192.168.1.10/24, gateway 192.168.1.1" + } else { + "Offers 192.168.1.10/24 on the local LAN" + }; + self.broadcast_on_lan( + CLIENT, + Proto::Discover, + "PC1 broadcasts to find a DHCP server".into(), + "Switch floods Discover on the LAN", + ); + self.send(server, CLIENT, Proto::Offer, offer); + self.broadcast_on_lan( + CLIENT, + Proto::DhcpRequest, + "PC1 broadcasts its selected offer".into(), + "All DHCP servers hear the choice", + ); + self.send( + server, + CLIENT, + Proto::DhcpAck, + "Selected server grants the lease", + ); + self.last().note = "PC1 configures 192.168.1.10/24".into(); + } + + fn dns(&mut self) { + let authority = self.topo.authority.expect("DNS preset has an authority"); + self.resolve_on_lan(self.topo.router().unwrap_or(SERVER)); + self.send( + CLIENT, + SERVER, + Proto::DnsQuery, + "PC1 asks its resolver for example.test", + ); + self.send( + SERVER, + authority, + Proto::DnsQuery, + "Cache miss: resolver asks the authority", + ); + self.send( + authority, + SERVER, + Proto::DnsResponse, + "Authority answers: 203.0.113.10", + ); + self.send( + SERVER, + CLIENT, + Proto::DnsResponse, + "Resolver caches the answer and replies", + ); + self.last().note = "PC1 receives the address 203.0.113.10".into(); + } + + fn traceroute(&mut self) { + let mut destination_ttl = 1; + if let Some(router) = self.topo.router() { + let expired = self.send(CLIENT, router, Proto::Probe, "Probe 1 starts with TTL 1"); + for step in expired.iter_mut() { + step.ttl = Some(1); + } + expired.last_mut().unwrap().note = "Router drops the probe: TTL expires".into(); + self.send( + router, + CLIENT, + Proto::TtlExceeded, + "Router sends ICMP Time Exceeded", + ); + self.last().note = "Hop 1 recorded: 192.168.1.1".into(); + destination_ttl = 2; + } + let router = self.topo.router(); + let probe = self.send( + CLIENT, + SERVER, + Proto::Probe, + format!("Probe starts with TTL {destination_ttl}"), + ); + for step in probe { + step.ttl = Some(destination_ttl - u8::from(router == Some(step.from))); + if router == Some(step.from) { + step.note = "Router forwards with TTL 1".into(); + } else if router.is_none() && step.legs.contains(&SERVER) { + step.note = "Server receives the probe with TTL 1".into(); + } + } + self.send( + SERVER, + CLIENT, + Proto::PortUnreachable, + "Server returns ICMP Port Unreachable", + ); + let target_ip = self.topo.devices[usize::from(SERVER)].ip; + self.last().note = format!("Hop {destination_ttl}: {target_ip}. Trace complete"); + } +} + +pub fn build(scenario: Scenario, topo: &Topology) -> Vec { + let mut exchange = Exchange { + topo, + switch: topo.switch(), + learned: Vec::new(), + events: Vec::new(), + }; + match scenario { + Scenario::Ping => exchange.ping(), + Scenario::Arp => exchange.arp(), + Scenario::Tcp => exchange.tcp(), + Scenario::Dhcp => exchange.dhcp(), + Scenario::Dns => exchange.dns(), + Scenario::Traceroute => exchange.traceroute(), + } + exchange.events +} diff --git a/community/network/src/tables.rs b/community/network/src/tables.rs new file mode 100644 index 0000000..8e3e875 --- /dev/null +++ b/community/network/src/tables.rs @@ -0,0 +1,102 @@ +//! Tables (switch MAC table, ARP caches) recomputed as a pure replay of events. +//! +//! `replay(events, done)` returns the state after the first `done` events completed; +//! rows keep their insertion order and the event index that inserted them, so the +//! panel can highlight what the last event learned. + +use super::scenario::Event; + +/// A learning event applied when its frame reaches the next device. +#[derive(Clone, PartialEq, Eq, Debug)] +pub enum TableUpdate { + /// A switch learned the source MAC of a frame entering on `port`. + Mac { + port: &'static str, + mac: &'static str, + device: u8, + }, + /// A host cached an IP↔MAC pair in its ARP table. + Arp { + device: u8, + ip: &'static str, + mac: &'static str, + }, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct MacRow { + pub port: &'static str, + pub mac: &'static str, + pub device: u8, + pub at: usize, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct ArpRow { + pub device: u8, + pub ip: &'static str, + pub mac: &'static str, + pub at: usize, +} + +#[derive(Debug, Default, PartialEq, Eq)] +pub struct TableState { + pub mac: Vec, + pub arp: Vec, +} + +impl TableState { + /// Event index of the most recent row insert (exercised by the unit tests). + #[cfg(test)] + #[must_use] + pub fn last_event(&self) -> Option { + let mac = self.mac.last().map(|r| r.at); + let arp = self.arp.last().map(|r| r.at); + match (mac, arp) { + (Some(a), Some(b)) => Some(a.max(b)), + (Some(a), None) | (None, Some(a)) => Some(a), + (None, None) => None, + } + } +} + +#[must_use] +pub fn replay(events: &[Event], done: usize) -> TableState { + let mut state = TableState::default(); + for (index, event) in events.iter().take(done).enumerate() { + let Some(update) = &event.table else { continue }; + match update { + TableUpdate::Mac { port, mac, device } => { + let (port, mac, device) = (*port, *mac, *device); + if !state + .mac + .iter() + .any(|row| row.mac == mac && row.device == device) + { + state.mac.push(MacRow { + port, + mac, + device, + at: index, + }); + } + } + TableUpdate::Arp { device, ip, mac } => { + let (device, ip, mac) = (*device, *ip, *mac); + if !state + .arp + .iter() + .any(|row| row.device == device && row.ip == ip) + { + state.arp.push(ArpRow { + device, + ip, + mac, + at: index, + }); + } + } + } + } + state +} diff --git a/community/network/src/tests.rs b/community/network/src/tests.rs new file mode 100644 index 0000000..c1769ea --- /dev/null +++ b/community/network/src/tests.rs @@ -0,0 +1,773 @@ +//! Native unit tests: scenario sequencing, table replay, timeline behaviour, +//! parameter validation and render determinism. + +use super::*; +use crate::animathio::plugin::types::DrawCommand; +use crate::scenario::{Event, Proto, Scenario, TableKind}; +use crate::topology::{topology, Topology, CLIENT, PEER, SERVER}; + +fn pv(id: &str, value: ParamValue) -> ParamEntry { + ParamEntry { + id: id.into(), + value, + } +} + +fn both_topologies() -> Vec<&'static Topology> { + vec![topology(false, false), topology(true, false)] +} + +fn build_all() -> Vec<(&'static Topology, Scenario, Vec)> { + let mut out = Vec::new(); + for routed in [false, true] { + for name in SCENARIOS { + let scenario = Scenario::parse(name).unwrap(); + let topo = topology(routed, scenario == Scenario::Dns); + out.push((topo, scenario, crate::scenario::build(scenario, topo))); + } + } + out +} + +fn find(events: &[Event], proto: Proto) -> Option { + events.iter().position(|e| e.proto == proto) +} + +#[test] +fn every_hop_is_a_real_link() { + for (topo, scenario, events) in build_all() { + for event in &events { + assert!( + !event.legs.is_empty() && event.legs.len() <= topo.devices.len(), + "{scenario:?} event with too many legs" + ); + for &leg in &event.legs { + assert!( + topo.neighbors(event.from).any(|(peer, _)| peer == leg), + "{scenario:?} on {}: {} → {} is not a link", + topo.label, + topo.devices[event.from as usize].name, + topo.devices[leg as usize].name + ); + } + } + } +} + +#[test] +fn scenarios_are_bounded_and_deterministic() { + for (topo, scenario, events) in build_all() { + assert!( + (4..=32).contains(&events.len()), + "{scenario:?} on {}", + topo.label + ); + let again = crate::scenario::build(scenario, topo); + assert_eq!( + events, again, + "{scenario:?} on {} is not deterministic", + topo.label + ); + } +} + +#[test] +fn ping_orders_arp_before_echo() { + for topo in both_topologies() { + let events = crate::scenario::build(Scenario::Ping, topo); + let reply = find(&events, Proto::ArpReply).expect("ping has an ARP reply"); + let echo = find(&events, Proto::Echo).expect("ping has an echo"); + assert!(reply < echo, "ARP reply must precede the first echo"); + let request = find(&events, Proto::ArpReq).expect("ping has an ARP request"); + assert!( + request < reply, + "ARP broadcast must precede the unicast reply" + ); + let echo_reply = find(&events, Proto::EchoReply).expect("ping has an echo reply"); + assert!(echo < echo_reply); + // The request is a broadcast flood; the reply is unicast. + assert!(events[request].broadcast); + assert!(!events[reply].broadcast); + } +} + +#[test] +fn tcp_handshake_then_http_then_close() { + for topo in both_topologies() { + let events = crate::scenario::build(Scenario::Tcp, topo); + let hops = topo.path(CLIENT, SERVER).len() - 1; + let messages = [ + (CLIENT, Proto::Syn, SERVER), + (SERVER, Proto::SynAck, CLIENT), + (CLIENT, Proto::Ack, SERVER), + (CLIENT, Proto::Get, SERVER), + (SERVER, Proto::Ok200, CLIENT), + (CLIENT, Proto::Fin, SERVER), + (SERVER, Proto::FinAck, CLIENT), + (CLIENT, Proto::Ack, SERVER), + ]; + assert_eq!(events.len(), messages.len() * hops); + for (message, (from, proto, to)) in events.chunks_exact(hops).zip(messages) { + assert_eq!(message[0].from, from); + assert!(message.iter().all(|hop| hop.proto == proto)); + assert!(message.last().unwrap().legs.contains(&to)); + } + let first_switch_egress = &events[1]; + assert_eq!( + first_switch_egress.legs.len(), + if topo.router().is_some() { 1 } else { 2 } + ); + assert!(!first_switch_egress.broadcast); + } +} + +#[test] +fn dhcp_is_dora() { + for topo in both_topologies() { + let events = crate::scenario::build(Scenario::Dhcp, topo); + let protos: Vec = events.iter().map(|e| e.proto).collect(); + assert_eq!( + protos, + vec![ + Proto::Discover, + Proto::Discover, + Proto::Offer, + Proto::Offer, + Proto::DhcpRequest, + Proto::DhcpRequest, + Proto::DhcpAck, + Proto::DhcpAck, + ], + "DHCP must follow D-O-R-A" + ); + // Discover and Request are broadcast floods; Offer/Ack come back unicast. + assert!(events[0].broadcast && events[1].broadcast); + assert!(!events[2].broadcast); + assert!(!events[6].broadcast); + } +} + +#[test] +fn dns_resolves_after_arp() { + for routed in [false, true] { + let topo = topology(routed, true); + let authority = topo.authority.unwrap(); + let events = crate::scenario::build(Scenario::Dns, topo); + let first_query = find(&events, Proto::DnsQuery).unwrap(); + let arp_reply = find(&events, Proto::ArpReply).unwrap(); + assert!(arp_reply < first_query); + assert_eq!(events[first_query].from, CLIENT); + + let resolver_hops = topo.path(CLIENT, SERVER).len() - 1; + let authority_hops = topo.path(SERVER, authority).len() - 1; + let second_query = first_query + resolver_hops; + assert_eq!(events[second_query].proto, Proto::DnsQuery); + assert_eq!(events[second_query].from, SERVER); + assert!(events[second_query - 1].legs.contains(&SERVER)); + + let answer = second_query + authority_hops; + assert_eq!(events[answer].from, authority); + assert!(events[answer - 1].legs.contains(&authority)); + assert_eq!(events[answer].proto, Proto::DnsResponse); + assert!(events[answer].note.contains("203.0.113.10")); + + let resolver_answer = answer + authority_hops; + assert_eq!(events[resolver_answer].from, SERVER); + assert!(events[resolver_answer - 1].legs.contains(&SERVER)); + assert_eq!(events.last().unwrap().legs, [CLIENT]); + } +} + +#[test] +fn traceroute_hop_count_matches_router_count() { + for topo in both_topologies() { + let events = crate::scenario::build(Scenario::Traceroute, topo); + let exceeded = events + .iter() + .filter(|e| e.proto == Proto::TtlExceeded) + .count(); + let routers = usize::from(topo.router().is_some()); + // One Time Exceeded per router, crossing two links (router → switch → PC1). + assert_eq!( + exceeded, + 2 * routers, + "Time Exceeded events on {}", + topo.label + ); + let hops = events.iter().filter(|e| e.note.starts_with("Hop ")).count(); + assert_eq!(hops, routers + 1, "recorded hops on {}", topo.label); + let ttls: Vec<_> = events.iter().filter_map(|event| event.ttl).collect(); + assert_eq!( + ttls, + if routers == 1 { + vec![1, 1, 2, 2, 1] + } else { + vec![1, 1] + } + ); + assert!(events.iter().any(|e| e.proto == Proto::PortUnreachable)); + assert!(events.last().unwrap().note.contains("Trace complete")); + } +} + +#[test] +fn arp_scenario_resolves_then_pings_without_broadcast() { + for topo in both_topologies() { + let events = crate::scenario::build(Scenario::Arp, topo); + let last_broadcast = events.iter().rposition(|e| e.broadcast).unwrap(); + let echo = find(&events, Proto::Echo).unwrap(); + assert!( + last_broadcast < echo, + "the follow-up ping must use the cache, not ARP" + ); + } +} + +#[test] +fn broadcast_flood_fans_out_to_every_other_switch_port() { + let single = topology(false, false); + let sw = single.switch(); + let events = crate::scenario::build(Scenario::Ping, single); + let flood = &events[1]; + assert_eq!(flood.from, sw); + assert_eq!( + flood.legs.len(), + 2, + "single-switch floods to PC2 and the server" + ); + let through = topology(true, false); + let events = crate::scenario::build(Scenario::Ping, through); + assert_eq!(events[1].legs.len(), 1, "through-router has one other port"); + assert_eq!(events[1].legs, [through.router().unwrap()]); + assert_eq!(flood.legs, [1, 3]); +} + +#[test] +fn table_replay_is_monotone_and_prefix_consistent() { + for (topo, scenario, events) in build_all() { + let full = crate::tables::replay(&events, events.len()); + let mut previous = crate::tables::TableState::default(); + for done in 0..=events.len() { + let state = crate::tables::replay(&events, done); + let truncated = crate::tables::replay(&events[..done], usize::MAX); + assert_eq!(state, truncated, "{scenario:?} on {}", topo.label); + assert!(state.mac.starts_with(&previous.mac)); + assert!(state.arp.starts_with(&previous.arp)); + assert!(state.mac.iter().all(|row| row.at < done)); + assert!(state.arp.iter().all(|row| row.at < done)); + assert!(full.mac.starts_with(&state.mac)); + assert!(full.arp.starts_with(&state.arp)); + previous = state; + } + } +} + +#[test] +fn ping_through_router_fills_both_tables() { + let topo = topology(true, false); + let events = crate::scenario::build(Scenario::Ping, topo); + let state = crate::tables::replay(&events, events.len()); + assert_eq!(state.arp.len(), 1, "PC1 cached exactly the gateway"); + assert_eq!(state.arp[0].ip, "192.168.1.1"); + assert_eq!(state.mac.len(), 2, "switch learned PC1 and the router"); + let ats: Vec = state.mac.iter().map(|r| r.at).collect(); + assert!( + ats.windows(2).all(|w| w[0] < w[1]), + "insertion order is stable" + ); +} + +#[test] +fn tables_start_empty() { + for (_, _, events) in build_all() { + let state = crate::tables::replay(&events, 0); + assert!(state.mac.is_empty() && state.arp.is_empty()); + assert!(state.last_event().is_none()); + } +} + +#[test] +fn switch_flood_notes_match_the_number_of_egress_ports() { + for routed in [false, true] { + let topo = topology(routed, false); + let events = crate::scenario::build(Scenario::Tcp, topo); + let flood = events + .iter() + .find(|event| event.note.starts_with("Unknown MAC")) + .expect("the first TCP SYN floods the switch"); + assert_eq!(flood.from, topo.switch()); + let other_ports = topo.neighbors(topo.switch()).count() - 1; + assert_eq!(flood.legs.len(), other_ports); + assert_eq!( + flood.note, + if routed { + "Unknown MAC: flood to the only other port" + } else { + "Unknown MAC: flood to every other port" + } + ); + } +} + +#[test] +fn auto_table_matches_the_scenario_and_topology() { + let single = topology(false, false); + let routed = topology(true, false); + assert_eq!(Scenario::Ping.auto_table(single), TableKind::Arp); + assert_eq!(Scenario::Ping.auto_table(routed), TableKind::Arp); + assert_eq!( + Scenario::Dns.auto_table(topology(true, true)), + TableKind::Arp + ); + assert_eq!(Scenario::Traceroute.auto_table(routed), TableKind::Route); + assert_eq!( + Scenario::Traceroute.auto_table(single), + TableKind::Mac, + "single-switch traceroute has no router to route with" + ); + for topo in [single, routed] { + for scenario in [Scenario::Arp, Scenario::Tcp, Scenario::Dhcp] { + assert_eq!(scenario.auto_table(topo), TableKind::Mac); + } + } +} + +#[test] +fn auto_traceroute_table_on_one_switch_shows_mac_learning() { + let size = Size { + width: 1280, + height: 720, + }; + let texts = |params: &[ParamEntry]| -> Vec { + render(params, size) + .unwrap() + .elements + .iter() + .filter_map(|element| match element { + DrawCommand::TextRun(run) => Some(run.text.clone()), + _ => None, + }) + .collect() + }; + let single = render_params(&[ + ("scenario", ParamValue::EnumChoice("traceroute".into())), + ("topology", ParamValue::EnumChoice("single-switch".into())), + ]); + let titles = texts(&single); + assert!(titles.iter().any(|t| t == "Switch MAC table")); + assert!(titles.iter().any(|t| t.contains("02:11:22:33:44:01"))); + let routed = render_params(&[ + ("scenario", ParamValue::EnumChoice("traceroute".into())), + ("topology", ParamValue::EnumChoice("through-router".into())), + ]); + assert!(texts(&routed).iter().any(|t| t == "Router routing table")); + // The manual choice still names the absent router honestly. + let manual = render_params(&[ + ("scenario", ParamValue::EnumChoice("traceroute".into())), + ("topology", ParamValue::EnumChoice("single-switch".into())), + ("table", ParamValue::EnumChoice("route".into())), + ]); + assert!(texts(&manual).iter().any(|t| t == "No router on this LAN")); +} + +#[test] +fn traceroute_notes_the_server_arrival_inside_the_flood() { + let single = topology(false, false); + let events = crate::scenario::build(Scenario::Traceroute, single); + let arrival = events + .iter() + .find(|event| event.note == "Server receives the probe with TTL 1") + .expect("single-switch trace notes the server's arrival"); + assert!( + arrival.legs.contains(&SERVER), + "the note rides the server leg" + ); + // The same flood also copies the probe to PC2. + assert!(arrival.legs.contains(&PEER)); + assert_eq!(arrival.ttl, Some(1)); + let routed = topology(true, false); + let events = crate::scenario::build(Scenario::Traceroute, routed); + assert!( + events + .iter() + .all(|event| event.note != "Server receives the probe with TTL 1"), + "routed hops are unicast; the forward note covers arrival" + ); + let forward = events + .iter() + .find(|event| event.note == "Router forwards with TTL 1") + .expect("router forward note"); + assert!(forward.legs.contains(&SERVER)); + assert_eq!(forward.ttl, Some(1)); +} + +#[test] +fn enum_params_reject_wrong_types_like_bad_strings() { + let size = Size { + width: 1280, + height: 720, + }; + let message = |params: &[ParamEntry]| { + render(params, size) + .expect_err("a bad value must be rejected") + .message + }; + let expected = "Unsupported topology. Expected one of single-switch, through-router"; + assert_eq!( + message(&[pv("topology", ParamValue::EnumChoice("token-ring".into()))]), + expected + ); + assert_eq!( + message(&[pv("topology", ParamValue::Number(2.0))]), + expected + ); + assert_eq!(message(&[pv("topology", ParamValue::Bool(true))]), expected); + let expected = "Unsupported scenario. Expected one of ping, arp, tcp, dhcp, dns, traceroute"; + assert_eq!( + message(&[pv("scenario", ParamValue::EnumChoice("ospf".into()))]), + expected + ); + assert_eq!( + message(&[pv("scenario", ParamValue::String("ospf".into()))]), + expected + ); + assert_eq!( + message(&[pv("scenario", ParamValue::Number(7.0))]), + expected + ); +} + +#[test] +fn timeline_completes_every_event() { + for n in [1_usize, 5, 18, 32] { + assert_eq!(crate::timeline::done(crate::timeline::position(1.0, n)), n); + assert_eq!(crate::timeline::done(crate::timeline::position(0.0, n)), 0); + } + // The last event is still playing just before the final hold. + let u = crate::timeline::position(0.93, 10); + assert_eq!(crate::timeline::playing(u, 10), Some(9)); +} + +#[test] +fn packet_flight_is_continuous_within_a_hop() { + // Eased position moves strictly forward and hits both endpoints exactly. + let mut previous = 0.0_f32; + for step in 1..=100 { + let t = crate::timeline::ease(step as f32 / 100.0); + assert!(t > previous, "eased flight went backwards at step {step}"); + assert!((0.0..=1.0).contains(&t)); + previous = t; + } + assert_eq!(crate::timeline::ease(0.0), 0.0); + assert_eq!(crate::timeline::ease(1.0), 1.0); +} + +fn render_params(values: &[(&str, ParamValue)]) -> Vec { + values.iter().map(|(id, v)| pv(id, v.clone())).collect() +} + +fn snapshot(params: &[ParamEntry]) -> String { + format!( + "{:?}", + render( + params, + Size { + width: 1280, + height: 720 + } + ) + .unwrap() + ) +} + +fn text_runs(scene: &Scene) -> usize { + scene + .elements + .iter() + .filter(|e| matches!(e, DrawCommand::TextRun(_))) + .count() +} + +#[test] +fn params_are_validated() { + let bad_number = [pv("progress", ParamValue::Number(f64::NAN))]; + assert!(render( + &bad_number, + Size { + width: 1280, + height: 720 + } + ) + .is_err()); + let bad_scenario = [pv("scenario", ParamValue::EnumChoice("ospf".into()))]; + assert!(render( + &bad_scenario, + Size { + width: 1280, + height: 720 + } + ) + .is_err()); + let bad_labels = [pv("labels", ParamValue::EnumChoice("tiny".into()))]; + assert!(render( + &bad_labels, + Size { + width: 1280, + height: 720 + } + ) + .is_err()); + let bad_table = [pv("table", ParamValue::EnumChoice("bgp".into()))]; + assert!(render( + &bad_table, + Size { + width: 1280, + height: 720 + } + ) + .is_err()); + let empty_canvas: [ParamEntry; 0] = []; + assert!( + render( + &empty_canvas, + Size { + width: 0, + height: 720 + } + ) + .is_err(), + "zero canvas is rejected" + ); + // Out-of-range numbers clamp instead of failing. + let clamped = [ + pv("steps", ParamValue::Number(1000.0)), + pv("packet_size", ParamValue::Number(99.0)), + pv("progress", ParamValue::Number(-3.0)), + ]; + assert!(render( + &clamped, + Size { + width: 1280, + height: 720 + } + ) + .is_ok()); +} + +#[test] +fn label_modes_change_the_scene() { + let none = render_params(&[ + ("scenario", ParamValue::EnumChoice("tcp".into())), + ("topology", ParamValue::EnumChoice("through-router".into())), + ("labels", ParamValue::EnumChoice("none".into())), + ]); + let brief = render_params(&[ + ("scenario", ParamValue::EnumChoice("tcp".into())), + ("topology", ParamValue::EnumChoice("through-router".into())), + ("labels", ParamValue::EnumChoice("brief".into())), + ]); + let full = render_params(&[ + ("scenario", ParamValue::EnumChoice("tcp".into())), + ("topology", ParamValue::EnumChoice("through-router".into())), + ("labels", ParamValue::EnumChoice("full".into())), + ]); + let size = Size { + width: 1280, + height: 720, + }; + let none = text_runs(&render(&none, size).unwrap()); + let brief = text_runs(&render(&brief, size).unwrap()); + let full = text_runs(&render(&full, size).unwrap()); + assert!( + none < brief && brief < full, + "text runs: none={none} brief={brief} full={full}" + ); +} + +#[test] +fn scenario_and_topology_change_the_scene() { + let ping = [ + pv("scenario", ParamValue::EnumChoice("ping".into())), + pv("progress", ParamValue::Number(0.6)), + ]; + let dhcp = [ + pv("scenario", ParamValue::EnumChoice("dhcp".into())), + pv("progress", ParamValue::Number(0.6)), + ]; + assert_ne!(snapshot(&ping), snapshot(&dhcp)); + let single = [ + pv("topology", ParamValue::EnumChoice("single-switch".into())), + pv("progress", ParamValue::Number(0.6)), + ]; + let through = [ + pv("topology", ParamValue::EnumChoice("through-router".into())), + pv("progress", ParamValue::Number(0.6)), + ]; + assert_ne!(snapshot(&single), snapshot(&through)); +} + +#[test] +fn progress_advances_the_scene() { + let mut previous = String::new(); + for step in 0..=20 { + let params = [pv("progress", ParamValue::Number(step as f64 / 20.0))]; + let snap = snapshot(¶ms); + if step > 0 { + assert_ne!( + snap, previous, + "progress {step}/20 did not change the scene" + ); + } + previous = snap; + } +} + +#[test] +fn render_is_deterministic_and_different_per_scenario() { + for scenario in SCENARIOS { + let params = [pv("scenario", ParamValue::EnumChoice(scenario.into()))]; + assert_eq!( + snapshot(¶ms), + snapshot(¶ms), + "{scenario} must be deterministic" + ); + } +} + +#[test] +fn steps_param_truncates_the_timeline() { + let short = [ + pv("steps", ParamValue::Number(3.0)), + pv("progress", ParamValue::Number(1.0)), + ]; + let snap = snapshot(&short); + // Only 3 of ping's 8+ events play: the scene differs from the full run. + let full = [pv("progress", ParamValue::Number(1.0))]; + assert_ne!(snap, snapshot(&full)); + // A step cap above the scenario length changes nothing. + let generous = [pv("steps", ParamValue::Number(200.0))]; + assert_eq!(snapshot(&generous), snapshot(&full)); +} + +#[test] +fn panels_can_be_hidden() { + let off = [ + pv("show_tables", ParamValue::Bool(false)), + pv("show_step_list", ParamValue::Bool(false)), + ]; + let snap = snapshot(&off); + let on: [ParamEntry; 0] = []; + assert_ne!(snap, snapshot(&on)); +} + +#[test] +fn small_canvas_renders_without_error() { + for (topo, scenario, _) in build_all() { + let topology_name = if topo.router().is_some() { + "through-router" + } else { + "single-switch" + }; + let params = render_params(&[ + ( + "scenario", + ParamValue::EnumChoice(scenario_name(scenario).into()), + ), + ("topology", ParamValue::EnumChoice(topology_name.into())), + ]); + for size in [(180, 320), (320, 180), (1280, 720), (1920, 1080)] { + let scene = render( + ¶ms, + Size { + width: size.0, + height: size.1, + }, + ); + assert!( + scene.is_ok(), + "{} on {} at {size:?}", + scenario_name(scenario), + topo.label + ); + } + } +} + +fn scenario_name(scenario: Scenario) -> &'static str { + match scenario { + Scenario::Ping => "ping", + Scenario::Arp => "arp", + Scenario::Tcp => "tcp", + Scenario::Dhcp => "dhcp", + Scenario::Dns => "dns", + Scenario::Traceroute => "traceroute", + } +} + +#[test] +fn router_uses_interface_macs() { + let topo = topology(true, false); + let sw = topo.switch(); + let rtr = topo.router().unwrap(); + assert_eq!(topo.mac_towards(rtr, sw), "02:22:33:44:55:01"); + assert_eq!(topo.mac_towards(rtr, 3), "02:22:33:44:55:02"); + assert_eq!(topo.mac_towards(0, sw), "02:11:22:33:44:01"); +} + +#[test] +fn describe_matches_manifest_contract() { + let manifest = crate::NetLab::describe(); + assert_eq!(manifest.version, "1.0.0"); + assert_eq!(manifest.kinds, vec!["clip-source".to_string()]); + assert!(manifest.params.len() <= 32, "at most 32 parameters"); + let ids: Vec<&str> = manifest.params.iter().map(|p| p.id.as_str()).collect(); + for required in [ + "scenario", + "topology", + "progress", + "steps", + "labels", + "show_tables", + "table", + "packet_size", + "accent", + "show_step_list", + "speed_lines", + ] { + assert!(ids.contains(&required), "missing param {required}"); + } +} + +#[test] +fn lease_appears_only_after_the_ack_reaches_the_client() { + let topo = topology(false, false); + let events = crate::scenario::build(Scenario::Dhcp, topo); + let scene_at = |slot: f32, steps: usize| { + let progress = + (slot + timeline::LEAD_IN) / (steps as f32 + timeline::LEAD_IN + timeline::LEAD_OUT); + let params = [ + pv("scenario", ParamValue::EnumChoice("dhcp".into())), + pv("topology", ParamValue::EnumChoice("single-switch".into())), + pv("progress", ParamValue::Number(f64::from(progress))), + pv("steps", ParamValue::Number(steps as f64)), + ]; + render( + ¶ms, + Size { + width: 1280, + height: 720, + }, + ) + .unwrap() + }; + let contains = |scene: Scene, text: &str| { + scene + .elements + .iter() + .any(|element| matches!(element, DrawCommand::TextRun(run) if run.text == text)) + }; + assert!(contains(scene_at(7.5, events.len()), "Awaiting lease")); + assert!(contains(scene_at(7.25, 7), "Awaiting lease")); + assert!(!contains(scene_at(8.1, events.len()), "Awaiting lease")); + assert!(contains(scene_at(8.1, events.len()), "192.168.1.10")); +} diff --git a/community/network/src/timeline.rs b/community/network/src/timeline.rs new file mode 100644 index 0000000..957a35f --- /dev/null +++ b/community/network/src/timeline.rs @@ -0,0 +1,90 @@ +//! `progress` → timeline mapping: which event is playing, which are done, and +//! where each packet sits on its link. Pure and continuous by construction. + +/// Idle lead-in before event 0 starts (in event slots). +pub const LEAD_IN: f32 = 0.5; +/// Hold after the last event completes (in event slots). +pub const LEAD_OUT: f32 = 0.25; + +/// Timeline position `u` for `progress`: event `i` occupies the slot `[i, i+1)`. +#[must_use] +pub fn position(progress: f32, events: usize) -> f32 { + let span = events as f32 + LEAD_IN + LEAD_OUT; + -LEAD_IN + progress.clamp(0.0, 1.0) * span +} + +/// Index of the event currently in flight, `None` before the first and during +/// the final hold. +#[must_use] +pub fn playing(u: f32, events: usize) -> Option { + if u < 0.0 { + return None; + } + let index = u.floor() as usize; + if index >= events { + None + } else { + Some(index) + } +} + +/// Number of fully completed events at timeline position `u`. +#[must_use] +pub fn done(u: f32) -> usize { + if u < 0.0 { + 0 + } else { + u.floor() as usize + } +} + +/// Smoothstep easing within one event slot. +#[must_use] +pub fn ease(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +/// Eased fraction of the current event slot (0..=1), `None` when idle. +#[must_use] +pub fn phase(u: f32, events: usize) -> Option { + playing(u, events).map(|index| ease(u - index as f32)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn endpoints_are_exact() { + let u0 = position(0.0, 10); + assert!((u0 - -LEAD_IN).abs() < 1e-6); + let u1 = position(1.0, 10); + assert!((u1 - (10.0 + LEAD_OUT)).abs() < 1e-6); + assert_eq!(done(u0), 0); + assert_eq!(done(u1), 10); + assert_eq!(playing(u0, 10), None); + assert_eq!(playing(u1, 10), None); + assert_eq!(playing(position(0.9, 10), 10), Some(9)); + assert!(phase(position(0.5, 10), 10).is_some()); + assert_eq!(phase(u1, 10), None); + } + + #[test] + fn phases_move_forward_and_stay_in_slot() { + for slot in 0..8_usize { + let mut previous = 0.0_f32; + for step in 0..20 { + let u = slot as f32 + step as f32 / 20.0; + let t = phase(u, 8).unwrap(); + assert!((0.0..=1.0).contains(&t)); + assert!(t >= previous - 1e-6, "phase went backwards in slot {slot}"); + previous = t; + } + assert_eq!( + phase(slot as f32 + 1.0, 8), + if slot + 1 < 8 { Some(0.0) } else { None } + ); + } + } +} diff --git a/community/network/src/topology.rs b/community/network/src/topology.rs new file mode 100644 index 0000000..c1e1938 --- /dev/null +++ b/community/network/src/topology.rs @@ -0,0 +1,337 @@ +//! Teaching topologies, link paths and layout anchors. +//! +//! Everything is static data; the drawing layer scales it into the free part of the +//! canvas, so a render is resolution-independent by construction. + +use std::collections::VecDeque; + +pub const CLIENT: u8 = 0; +pub const PEER: u8 = 1; +pub const SERVER: u8 = 3; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum DeviceKind { + Host, + Switch, + Router, + Server, +} + +#[derive(Clone, Copy)] +pub struct Device { + pub name: &'static str, + pub kind: DeviceKind, + /// Management/primary IPv4 address, `""` for the layer-2-only switch. + pub ip: &'static str, + pub mac: &'static str, +} + +#[derive(Clone, Copy)] +pub struct Link { + pub a: u8, + /// Port name on device `a`. + pub a_port: &'static str, + pub b: u8, + /// Port name on device `b`. + pub b_port: &'static str, +} + +#[derive(Clone, Copy)] +pub struct RouteRow { + pub destination: &'static str, + pub kind: &'static str, + pub interface: &'static str, +} + +pub struct Topology { + pub label: &'static str, + pub devices: &'static [Device], + pub links: &'static [Link], + /// The authoritative DNS service, present in the DNS lesson. + pub authority: Option, + /// Static routing-table rows of the router, empty without one. + pub routes: &'static [RouteRow], + /// Layout anchor per device as fractions of the free diagram rectangle. + pub anchors: &'static [(f32, f32)], + /// True when the layout draws labels above the device box. + pub label_above: &'static [bool], +} + +const PC1_MAC: &str = "02:11:22:33:44:01"; +const PC2_MAC: &str = "02:11:22:33:44:02"; +const SRV_MAC: &str = "02:11:22:33:44:0A"; +const SW_MAC: &str = "02:11:22:33:00:0B"; +const RTR_MAC0: &str = "02:22:33:44:55:01"; +const RTR_MAC1: &str = "02:22:33:44:55:02"; +const RTR_MAC2: &str = "02:22:33:44:55:03"; + +/// `single-switch`: PC1, PC2 and a server on one LAN behind one switch. +const SINGLE_SWITCH: Topology = Topology { + label: "Single LAN · 192.168.1.0/24", + devices: &[ + Device { + name: "PC1", + kind: DeviceKind::Host, + ip: "192.168.1.10", + mac: PC1_MAC, + }, + Device { + name: "PC2", + kind: DeviceKind::Host, + ip: "192.168.1.20", + mac: PC2_MAC, + }, + Device { + name: "Switch", + kind: DeviceKind::Switch, + ip: "", + mac: SW_MAC, + }, + Device { + name: "Server", + kind: DeviceKind::Server, + ip: "192.168.1.50", + mac: SRV_MAC, + }, + ], + links: &[ + Link { + a: 0, + a_port: "Eth0", + b: 2, + b_port: "Fa0/1", + }, + Link { + a: 1, + a_port: "Eth0", + b: 2, + b_port: "Fa0/2", + }, + Link { + a: 3, + a_port: "Eth0", + b: 2, + b_port: "Fa0/3", + }, + ], + authority: None, + routes: &[], + anchors: &[(0.16, 0.68), (0.84, 0.68), (0.50, 0.68), (0.50, 0.30)], + label_above: &[false, false, false, true], +}; + +/// `through-router`: PC1 — switch — router — server across two subnets. +const THROUGH_ROUTER: Topology = Topology { + label: "Routed LANs · 192.168.1.0/24 and 10.0.0.0/24", + devices: &[ + Device { + name: "PC1", + kind: DeviceKind::Host, + ip: "192.168.1.10", + mac: PC1_MAC, + }, + Device { + name: "Switch", + kind: DeviceKind::Switch, + ip: "", + mac: SW_MAC, + }, + Device { + name: "Router", + kind: DeviceKind::Router, + ip: "192.168.1.1", + mac: RTR_MAC0, + }, + Device { + name: "Server", + kind: DeviceKind::Server, + ip: "10.0.0.50", + mac: SRV_MAC, + }, + ], + links: &[ + Link { + a: 0, + a_port: "Eth0", + b: 1, + b_port: "Fa0/1", + }, + Link { + a: 1, + a_port: "Fa0/2", + b: 2, + b_port: "Gi0/0", + }, + Link { + a: 2, + a_port: "Gi0/1", + b: 3, + b_port: "Eth0", + }, + ], + authority: None, + routes: &[ + RouteRow { + destination: "192.168.1.0/24", + kind: "Connected", + interface: "Gi0/0", + }, + RouteRow { + destination: "10.0.0.0/24", + kind: "Connected", + interface: "Gi0/1", + }, + ], + anchors: &[(0.10, 0.55), (0.37, 0.55), (0.63, 0.55), (0.90, 0.55)], + label_above: &[false, false, false, false], +}; + +static LOCAL_DNS: Topology = Topology { + devices: &[ + SINGLE_SWITCH.devices[0], + Device { + name: "Authority", + kind: DeviceKind::Server, + ..SINGLE_SWITCH.devices[1] + }, + SINGLE_SWITCH.devices[2], + Device { + name: "Resolver", + ..SINGLE_SWITCH.devices[3] + }, + ], + authority: Some(PEER), + ..SINGLE_SWITCH +}; + +static ROUTED_DNS: Topology = Topology { + label: "Routed LANs · client, resolver and authority", + devices: &[ + THROUGH_ROUTER.devices[0], + THROUGH_ROUTER.devices[1], + THROUGH_ROUTER.devices[2], + Device { + name: "Resolver", + ..THROUGH_ROUTER.devices[3] + }, + Device { + name: "Authority", + kind: DeviceKind::Server, + ip: "10.0.1.53", + mac: "02:11:22:33:44:0B", + }, + ], + links: &[ + THROUGH_ROUTER.links[0], + THROUGH_ROUTER.links[1], + THROUGH_ROUTER.links[2], + Link { + a: 2, + a_port: "Gi0/2", + b: 4, + b_port: "Eth0", + }, + ], + routes: &[ + THROUGH_ROUTER.routes[0], + THROUGH_ROUTER.routes[1], + RouteRow { + destination: "10.0.1.0/24", + kind: "Connected", + interface: "Gi0/2", + }, + ], + anchors: &[ + (0.12, 0.64), + (0.37, 0.64), + (0.62, 0.64), + (0.88, 0.64), + (0.88, 0.28), + ], + label_above: &[false, false, false, false, true], + authority: Some(4), +}; + +impl Topology { + pub fn switch(&self) -> u8 { + self.device_of_kind(DeviceKind::Switch) + .expect("each preset has a switch") + } + + pub fn router(&self) -> Option { + self.device_of_kind(DeviceKind::Router) + } + + fn device_of_kind(&self, kind: DeviceKind) -> Option { + self.devices + .iter() + .position(|device| device.kind == kind) + .map(|index| index as u8) + } + + pub fn neighbors(&self, device: u8) -> impl Iterator + '_ { + self.links.iter().filter_map(move |link| { + if link.a == device { + Some((link.b, link.a_port)) + } else if link.b == device { + Some((link.a, link.b_port)) + } else { + None + } + }) + } + + pub fn port_towards(&self, device: u8, peer: u8) -> &'static str { + self.neighbors(device) + .find_map(|(neighbor, port)| (neighbor == peer).then_some(port)) + .expect("adjacent nodes in a preset path") + } + + pub fn mac_towards(&self, device: u8, peer: u8) -> &'static str { + let device_info = &self.devices[usize::from(device)]; + if device_info.kind != DeviceKind::Router { + return device_info.mac; + } + match self.port_towards(device, peer) { + "Gi0/0" => RTR_MAC0, + "Gi0/1" => RTR_MAC1, + "Gi0/2" => RTR_MAC2, + _ => unreachable!("router port in a preset"), + } + } + + /// All presets are small connected trees, so each pair has one physical path. + pub fn path(&self, from: u8, to: u8) -> Vec { + let mut parents = vec![None; self.devices.len()]; + parents[usize::from(from)] = Some(from); + let mut queue = VecDeque::from([from]); + while let Some(node) = queue.pop_front() { + if node == to { + let mut path = vec![node]; + while let Some(&last) = path.last() { + if last == from { + path.reverse(); + return path; + } + path.push(parents[usize::from(last)].expect("visited node has a parent")); + } + } + for (neighbor, _) in self.neighbors(node) { + if parents[usize::from(neighbor)].is_none() { + parents[usize::from(neighbor)] = Some(node); + queue.push_back(neighbor); + } + } + } + unreachable!("preset connects all devices") + } +} + +pub fn topology(through_router: bool, dns: bool) -> &'static Topology { + match (through_router, dns) { + (false, false) => &SINGLE_SWITCH, + (true, false) => &THROUGH_ROUTER, + (false, true) => &LOCAL_DNS, + (true, true) => &ROUTED_DNS, + } +} diff --git a/community/network/wit/plugin.wit b/community/network/wit/plugin.wit new file mode 100644 index 0000000..b6820d9 --- /dev/null +++ b/community/network/wit/plugin.wit @@ -0,0 +1,582 @@ +package animathio:plugin@1.1.0; + +/// Shared data types for vector graphics, parameter schemas and plugin manifests. +interface types { + /// 2D dimensions in integer pixels. + record size { + width: u32, + height: u32, + } + + /// Finite 2D coordinates: x right, y down. Scene.coordinate-space selects units. + record point { + x: f32, + y: f32, + } + + /// Straight-alpha 8-bit RGBA color. + record color { + r: u8, + g: u8, + b: u8, + a: u8, + } + + /// Path segment command. + variant path-verb { + move-to(point), + line-to(point), + quad-to(tuple), + cubic-to(tuple), + close, + } + + /// Sequence of path commands forming one or more contours. + type path = list; + + /// Line cap style at path endpoints. + enum stroke-cap { + butt, + round, + square, + } + + /// Line join style at path vertices. + enum stroke-join { + miter, + round, + bevel, + } + + /// Outline styling parameters. + record stroke-style { + width: f32, + color: color, + cap: stroke-cap, + join: stroke-join, + } + + /// Horizontal alignment in the available canvas width. + enum text-alignment { left, center, right } + + /// Text run layout element. + record text-element { + align: text-alignment, + text: string, + font-size: f32, + x: f32, + y: f32, + color: color, + } + + /// Vector drawing command. + variant draw-command { + fill-path(tuple), + stroke-path(tuple), + text-run(text-element), + } + + /// canvas: pixels on the requested render canvas. normalized: local unit square, + /// with x scaled by width and y by height. Strokes are outlined in local + /// units then transformed with the paths (nonuniform scaling is allowed). + /// Normalized text-run font-size is a fraction of canvas height; x/y are + /// offsets from the centered text block. Values outside 0..1 are allowed. + enum coordinate-space { canvas, normalized } + + /// Evaluated vector scene composed of ordered draw commands. + record scene { + coordinate-space: coordinate-space, + elements: list, + } + + /// Axis-aligned bounding box in canvas coordinates. + record bbox { + min-x: f32, + min-y: f32, + max-x: f32, + max-y: f32, + } + + /// Result of host-side math typesetting. + record typeset-result { + paths: list, + bbox: bbox, + } + + /// Input language for host-side math typesetting. + enum math-mode { + latex, + typst, + } + + /// Finite inclusive range; min <= default <= max and step > 0 (UI hint). + record number-range { + min: f64, + max: f64, + default: f64, + step: f64, + } + + /// Color parameter declaration. + record color-param { + default: color, + } + + /// Text string parameter declaration. + record string-param { + default: string, + } + + /// Multiple-choice enum parameter declaration. + record enum-param { + options: list, + default: string, + } + + /// Boolean toggle parameter declaration. + record bool-param { + default: bool, + } + + /// 2D point parameter declaration. + record point-param { + default: point, + } + + /// Asset reference parameter declaration. + record asset-ref-param { + media-type: string, + default-asset: option, + } + + /// Supported parameter types. + variant param-kind { + %number(number-range), + %color(color-param), + %string(string-param), + enum-choice(enum-param), + %bool(bool-param), + %point(point-param), + asset-ref(asset-ref-param), + } + + /// Stable id, fallback human label and typed schema. Labels are not identifiers. + /// Translation keys and units may be supplied in manifest.metadata. + record param-spec { + id: string, + label: string, + kind: param-kind, + } + + /// Concrete value assigned to a parameter at evaluation time. + variant param-value { + %number(f64), + %color(color), + %string(string), + enum-choice(string), + %bool(bool), + %point(point), + asset-ref(string), + } + + /// Key-value parameter entry. + record param-entry { + id: string, + value: param-value, + } + + /// Map of parameter values passed to plugin invocations. + type param-map = list; + + /// Open classification: clip-source, effect, audio-effect, animation-preset + /// (1.1) or importer (1.1). The legacy animation kind has no execution world. + /// Unknown strings are metadata, never permission to invoke an unknown world. + type plugin-kind = string; + + /// Optional, namespaced advisory metadata. Unknown keys must be ignored. + /// Keys are unique; values are UTF-8, never executable content. Reserved + /// conventions: label-key, description-key, param..unit, + /// param..label-key and param..option..label-key; + /// prefix with effect.. for effect descriptors. No localization service + /// is implied: plain labels/messages remain mandatory fallbacks. + type metadata = list>; + + /// Extensible error code plus fallback diagnostic text and advisory details. + /// Known codes: invalid-input, limit-exceeded, service-failed, plugin-error. + /// Unknown codes are displayed using message; callers must not parse messages. + record diagnostic { + code: string, + message: string, + metadata: metadata, + } + + /// Plugin metadata and parameter schema. + record manifest { + name: string, + version: string, + description: string, + kinds: list, + metadata: metadata, + params: list, + } +} + +/// Host-provided services imported by plugins. +interface host { + use types.{path, math-mode, typeset-result, diagnostic}; + + /// Text shaping via host font engine. Size is pixels; positive and finite. + /// Returns glyph outline paths or an explicit diagnostic. + shape-text: func(text: string, font-size: f32) -> result, diagnostic>; + + /// Typeset math via the host typesetting engine. Returns glyph and rule + /// outline paths plus a tight bounding box. + typeset-math: func(source: string, mode: math-mode, font-size: f32) -> result; + + /// Extract double-quoted d attributes from SVG path elements, or accept raw + /// SVG path data. This is not a complete SVG renderer: transforms, styles, + /// other primitives and external resources are not interpreted. Empty input + /// succeeds with no paths; unsupported/non-path input returns a diagnostic. + svg-to-paths: func(svg-xml: string) -> result, diagnostic>; + + /// Hard limits configured for this host, as unique key/value pairs. + /// Stable keys: ticks-per-second, max-memory-bytes, max-table-elements, + /// fuel-per-call, epoch-interval-ms, epoch-deadline-ticks, max-effect-pixels, + /// effect-memory-bytes, effect-fuel-per-pixel, effect-epoch-deadline-ticks, + /// max-audio-block-frames, max-audio-state-bytes, audio-memory-bytes, + /// audio-fuel-per-sample, audio-epoch-deadline-ticks, max-audio-channels, + /// max-audio-sample-rate, max-shape-text-chars, max-shape-text-verbs, + /// max-svg-input-bytes, max-svg-verbs, max-typeset-verbs, + /// max-typeset-source-bytes, max-typeset-font-size-px, typeset-timeout-ms, + /// max-log-message-bytes, max-log-entries, max-effects-per-plugin (added in 1.0.x); since 1.1 also max-import-source-bytes, + /// import-memory-bytes, import-fuel-per-byte, import-epoch-deadline-ticks, + /// max-import-output-bytes, max-import-commands, max-sibling-file-bytes, + /// max-sibling-total-bytes, max-sibling-files, max-preset-keys. + /// Keys and units are specified in docs/plugins.md; unknown keys are ignored. + /// This reports policy, not remaining fuel or memory. Budgets reset per call. + limits: func() -> list>; + + /// Host logging for diagnostic and debug output. + log: func(message: string); +} + +/// Pixel-filter effects, added in API 0.2.1. +/// +/// A frame effect receives one straight-alpha sRGB RGBA8 frame and returns a +/// frame of the same size. The host enforces size, fuel, wall-clock and memory +/// limits on every call; see `SandboxLimits` in `plugin-host`. +interface frame-effects { + use types.{size, param-map, param-spec, diagnostic}; + + /// One filter offered by an effect plugin. + record effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step. Only `number` kinds are + /// supported; effect parameters are keyframeable numbers. + params: list, + } + + /// List the filters this plugin provides. + list-effects: func() -> list; + + /// Apply filter `effect` to `pixels`: `size.width * size.height * 4` bytes of + /// row-major straight-alpha sRGB RGBA8. Must return exactly the same number + /// of bytes. `time-ticks` is the clip-local source time. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + apply-frame: func(effect: string, pixels: list, size: size, params: param-map, time-ticks: s64) -> result, diagnostic>; +} + +/// Audio effects, added in API 0.2.2. +/// +/// An audio effect receives one block of interleaved f32 PCM and returns a block of +/// the same size. The host splits longer signals into contiguous blocks and carries an +/// opaque `state` blob from each call to the next, so filters, envelope followers and +/// other stateful processors work across block boundaries without the plugin keeping any +/// memory between calls. The host enforces block size, state size, fuel, wall-clock and +/// memory limits on every call; see `SandboxLimits` in `plugin-host`. +interface audio-effects { + use types.{param-map, param-spec, diagnostic}; + + /// One audio filter offered by an audio-effect plugin. + record audio-effect-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`), stored in projects. + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Numeric parameters with range, default and step; keyframeable on clip chains. + /// Only `number` kinds are supported. + params: list, + } + + /// A block of interleaved 32-bit float PCM. + record audio-block { + /// Frames per second (1..=768000). + sample-rate: u32, + /// Interleaved channel count (1..=32). + channels: u16, + /// Time of the first frame in the chain's own timeline, in ticks: clip-local for a + /// clip chain, project time for a track chain. + start-ticks: s64, + /// `frames * channels` finite samples, frame-major interleaving. Unclipped; + /// values may exceed 1.0. Preserve channel order (stereo is left, right). + /// No channel-layout negotiation or planar format is implied. + samples: list, + } + + /// Result of processing one block. + record block-output { + /// Exactly as many samples as the input block. + samples: list, + /// State to hand back with the next contiguous block, or none for stateless filters. + state: option>, + } + + /// List the audio filters this plugin provides. + list-audio-effects: func() -> list; + + /// Process one block with filter `effect`. `state` is `none` for the first block of a + /// signal; an empty blob is equivalent to none. Otherwise it is exactly the + /// nonempty blob the previous call returned. The call is a pure + /// function of its arguments. Returns a diagnostic on invalid input. + process-block: func(effect: string, block: audio-block, params: param-map, state: option>) -> result; +} + +/// Animation presets, added in API 1.1.0. +/// +/// A preset plugin turns a preset choice into ordinary keyframe curves. The host +/// converts the curves into one `Command::Batch` of keyframe edits, so rendering never +/// calls the plugin and undo restores the previous keyframes exactly. +interface animation-presets { + use types.{param-map, param-spec, diagnostic}; + + /// Where a preset sits in a clip's lifetime. The host places the window: + /// entrance at the clip start, exit at the clip end, emphasis centred on the clip. + enum preset-role { + entrance, + exit, + emphasis, + } + + /// One preset offered by an animation-preset plugin. + record preset-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Window placement. + role: preset-role, + /// Clip kinds the preset applies to; empty means every visual clip. Kind ids: + /// `video`, `image`, `vector` and `plugin:`. + applies-to: list, + /// Default window length in ticks (positive). + default-duration-ticks: s64, + /// Preset options: number, enum-choice or bool kinds only. + params: list, + } + + /// The clip a preset is generated for. + record clip-info { + /// Clip kind id, as in `applies-to`. + kind: string, + /// Visible clip length in ticks (positive). + duration-ticks: s64, + /// Length of one project frame in ticks (positive); a sampling hint. + frame-ticks: s64, + /// Current value of every animatable numeric target at the window's rest + /// point: the end of an entrance window, the start of an exit or emphasis + /// window. Keys are the curve target ids below. + rest: list>, + } + + /// Interpolation toward the next key, matching core keyframes. + enum curve-interpolation { + hold, + linear, + ease-in-out, + } + + /// One keyframe. `time-ticks` is relative to the window start, 0..=window. + record curve-key { + time-ticks: s64, + value: f64, + interpolation: curve-interpolation, + } + + /// Keyframes for one target: `opacity`, `x`, `y`, `scale-x`, `scale-y`, + /// `rotation` (radians) or `param:` for a numeric clip parameter. + record curve { + target: string, + keys: list, + } + + /// List the presets this plugin provides. + list-presets: func() -> list; + + /// Generate the curves for `preset` over a window of `window-ticks` (positive, + /// at most the clip duration). Pure in its arguments. Returns a diagnostic on + /// invalid input, e.g. a preset that does not apply to the clip kind. + generate: func(preset: string, clip: clip-info, window-ticks: s64, params: param-map) -> result, diagnostic>; +} + +/// Bounded reads of files next to an imported source, added in API 1.1.0. +/// Only importer components import this interface. +interface import-files { + use types.{diagnostic}; + + /// Read a file relative to the directory the host granted for this import. + /// `relative-path` uses `/` separators; absolute paths, `..` components and + /// paths that resolve (through symlinks) outside the directory are refused. + /// Per-file, total-byte and file-count caps apply per call; without a granted + /// directory every read fails with `invalid-input`. + read-sibling: func(relative-path: string) -> result, diagnostic>; +} + +/// Project importers, added in API 1.1.0. +/// +/// An importer turns source bytes into a versioned command document that the host +/// validates and replays onto a fresh project, plus content-addressed asset bytes. +interface importer { + use types.{param-map, param-spec, diagnostic}; + + /// One import format offered by an importer plugin. + record importer-descriptor { + /// Stable identifier, unique within the plugin (`[a-z0-9_-]`). + id: string, + /// Human-readable name for menus. + name: string, + /// One-line description for tooltips. + description: string, + /// Lower-case file extensions without the dot, e.g. `py`. + extensions: list, + /// Import options: string, number, enum-choice or bool kinds only. + params: list, + } + + /// The source being imported. + record import-source { + /// File name hint without directories (may be empty). + file-name: string, + /// Raw source bytes. + bytes: list, + } + + /// One asset referenced by the command document. + record imported-asset { + /// Lower-case hex BLAKE3 hash of `bytes`; the host recomputes it. + id: string, + /// Human-readable filename hint. + name: string, + /// Declared media type; decoders still probe the bytes. + media-type: string, + bytes: list, + } + + /// Non-fatal message severity. + enum message-severity { + info, + warning, + } + + /// One non-fatal observation; line and column are one-based, 0 when unknown. + record import-message { + severity: message-severity, + line: u32, + column: u32, + message: string, + snippet: string, + } + + /// A successful import. + record import-output { + /// UTF-8 JSON `{"version": 1, "commands": [...]}`: AniMathIO core commands + /// in their control-protocol serialization, replayed in order on an empty + /// project. Every command is validated; any failure rejects the import. + commands: string, + assets: list, + messages: list, + } + + /// List the formats this plugin imports. + list-importers: func() -> list; + + /// Import `source` with format `importer`. Pure apart from `read-sibling`. + run-import: func(importer: string, source: import-source, params: param-map) -> result; +} + +/// World for animation-preset plugins (`kinds = ["animation-preset"]`), API 1.1.0. +world animation-preset-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The presets themselves. + export animation-presets; +} + +/// World for importer plugins (`kinds = ["importer"]`), API 1.1.0. +world importer-plugin { + import host; + import import-files; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The import formats themselves. + export importer; +} + +/// World for audio-effect plugins (`kinds = ["audio-effect"]`): describe plus audio filters. +world audio-effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The audio filters themselves. + export audio-effects; +} + +/// World for effect plugins (`kinds = ["effect"]`): describe plus pixel filters. +/// Components for this world need no clip-source or animation exports. +world effect-plugin { + import host; + + use types.{manifest}; + + /// Describe the plugin and its kinds. + export describe: func() -> manifest; + + /// The pixel filters themselves. + export frame-effects; +} + +/// Pure vector generators. Frame and audio effects use their own worlds. +world source-plugin { + import host; + + use types.{manifest, scene, param-map, size, diagnostic}; + + /// Describe the plugin, its kinds and its parameter schema. + export describe: func() -> manifest; + + /// Render a vector scene, pure in its arguments. time-ticks is clip-local source + /// time in integer flicks (705600000 ticks/second). size is the render canvas. + /// An empty scene is valid; invalid geometry or traps fail the call. + export render-clip: func(params: param-map, time-ticks: s64, size: size) -> result; +}